How to import math functions in python? | math modules

Generally, we can use simple math functions like addition, subtraction, multiplication, and division so on.

but if we are in the case of using next-level math operations

let’s say for example if we are using the square root function

Example

a= sqrt(100)

Output

Traceback (most recent call last):
  File "<string>", line 1, in <module>
NameError: name 'sqrt' is not defined

Explanation

There are a lot of math operations that can be used in python

but for some additional math operations, we need to import a function module to get access them for that we asking our python to import that module for our operations

How to import a function ? in python

Syntax

import MODULE_NAME 

Explanation

here we are using the keyword Import followed by the Module name to say python that we need a module so that we can access their operations

Example

import math 

How to use operations after importing the math function ?

now we can use all the functions inside the math module after importing it

Syntax

MODULE_NAME.operation_name 

Explanation

we can use the operations inside the module by using the syntax above

Example

import math
a= math.sqrt(100)
b= math.sqrt(15)
print(a)
print(b)

Output

10.0
3.872983346207417

Explanation

  • Line1
    • here we are importing the math module
    • with import keyword and
    • module name math
  • Line2&3
    • here we assigning a variable a to store the values of our operations in it
    • by using the module_name followed by a (period) . then the operation name
  • Line 4&5
    • displaying the variable a to verify that our operations are done or not

How to access constants in the math function ?

Example

import math
print(math.pi)
print(math.e)

Output

3.141592653589793
2.718281828459045

Can we rename modules ? in Python

Syntax

import MODULE_NAME as any_letter of your choice

Explanation

we can use the modules with the allies character by using the syntax above

Example

import math as p
a= p.sqrt(100)
b= p.sqrt(15)
print(a)
print(b)

Output

10.0
3.872983346207417

Can we import perticular operations from modules ? in Python

Syntax

from MODULE_NAME import operation1,operation 2 . . . . . . . .

Example

from math import sqrt,pow
print(pow(2,3))
print(sqrt(25))

Output

8.0
5.0

Explanation

here we have imported only 2 operations from the math module

pow – power function (base, power)

sqrt – square root function (number)

List of Inbuilt modules in Python

these are the inbuilt modules of python

we can import any of them by using the keyword import and use the operations in it

1 Comment

Leave a reply

Edusera
Logo
Open chat
1
Scan the code
Hello!๐Ÿ‘‹
Can we help you?