In Python, modules are pre-written pieces of code that are used to perform common tasks like generating random numbers, performing mathematical operations, etc.
It allows us to reuse one or more functions in a program, even in the programs in which those functions have not been defined.
Actually module is a file with a .py extension that has definitions of all functions and variables.
The program in which we want to use functions or variables defined in the module simply import that particular module (or .py file).
The from…import statement
A module may contain definition for many variables and functions. When we import a module, we can use any variable or function defined in that module. But if we want to use only selected variables or functions, then we can use the from…import statement.
Example: 1
from math import pi print("pi=",pi)
Output:
pi= 3.141592653589793
To import more than one item from a module, use a comma separated list. For example, to import the value of pi and sqrt() from math module we can write,
from math import pi, sqrt
Example: 2
from math import pi,sqrt print("pi=",pi) print("Square root of 8 is=",sqrt(8))
Output:
pi= 3.141592653589793 Square root of 8 is= 2.8284271247461903
However, to import all the identifiers defined in sys module, we can use the from sys import * statement. However, we avoid using the import * statement as it confuses variable in our code with variables in the external module.
We can also import a module with a different name using the as a keyword. This is particularly more important when a module has either a long or confusing name.
Example: 3
from math import sqrt as square_root print("Square root of 12 is=",square_root(12))
Output:
Square root of 12 is= 3.4641016151377544
Python also allows us to pass command line arguments to a program. This can be done using the sys module. The argv variable in this module keeps a tract of command line arguments passes to the .py script.
Example: 4
import sys print(sys.argv)
To execute this code, go to Command Prompt (in Windows) and write
py filename.py “Hello World”
Output:
['op.py', 'Hello World']
Example: 5 for sum.py file:
import sys a=int(sys.argv[1]) b=int(sys.argv[2]) sum=a+b print("SUM=",sum)
To execute this code, go to Command Prompt (in Windows) and write
py sum.py 90 80
Output:
SUM= 170
Leave a comment