You are currently viewing Importing modules and using module functions and variables

Importing modules and using module functions and variables

To use a module in Python, you first need to import it. You can import an entire module or specific functions and variables from the module.

Here’s an example of importing the math module and using one of its functions:

import math

x = math.sqrt(25)
print(x)

This code imports the math module and uses its sqrt() function to calculate the square root of 25.

You can also import specific functions or variables from a module using the from keyword. Here’s an example:

from math import pi

print("The value of pi is", pi)

This code imports the pi variable from the math module and prints its value.

You can also import multiple functions or variables from a module using commas to separate them:

from math import sqrt, pow

x = sqrt(25)
y = pow(2, 3)

print(x, y)

This code imports the sqrt() and pow() functions from the math module and uses them to calculate the square root of 25 and the result of 2 raised to the power of 3.

It’s important to note that you should only import the functions and variables that you need, as importing unnecessary modules or functions can slow down your program and make it harder to read and understand.

Leave a Reply