Showing posts with label modules. Show all posts
Showing posts with label modules. Show all posts

Tuesday, 23 January 2024

Import multiple modules in one line in Python

We can import multiple modules in one line using comma-separated import statements.

This method is widely used and straightforward for importing multiple modules in one line. You just list the modules you need to import, separated by commas, within one import statement.

 

For example:

import random, math, statistics

 

This line imports the random , math, and statistics modules. You can then directly utilize these modules in your code by referencing their names.

 

import_multiple_modules.py

import random, math, statistics

print('Random Integer ', random.randint(1, 10))
print('PI : ', math.pi)
print('mean : ', statistics.mean([2, 3, 5, 7, 11]))

Output

Random Integer  8
PI :  3.141592653589793
mean :  5.6

 

Previous                                                 Next                                                 Home

Saturday, 5 December 2015

Python command line arguments

Python scripts accept any number of arguments from command line. This option facilitates us to configure Application at the time of running.

How to pass command line arguments
pyhon scriptname arg1 arg2 …argN

By using ‘sys’ module we can access command line arguments.

sys.argv[0] contains file name
sys.argv[1] contains first command line argument, sys.argv[2] contains second command line argument etc.,


arithmetic.py
def sum(a, b):
  return a+b

def subtract(a, b):
  return a-b
  
def mul(a,b):
  return a*b
  
def div(a, b):
  return a/b


main.py
import arithmetic

if __name__ == "__main__":
    import sys
    a = int(sys.argv[1])
    b = int(sys.argv[2])
    
    print(sys.argv[0])
    print("a = ", a, "b = ", b)
    print(arithmetic.sum(a,b))
    print(arithmetic.subtract(a,b))
    print(arithmetic.mul(a,b))
    print(arithmetic.div(a,b))


$ python3 main.py 10 11
main.py
a =  10 b =  11
21
-1
110
0.9090909090909091
  
$ python3 main.py 8 13
main.py
a =  8 b =  13
21
-5
104
0.6153846153846154




Previous                                                 Next                                                 Home

Python: import module in other module

Modules can import other modules using import statement.

arithmetic.py
def sum(a, b):
  return a+b

def subtract(a, b):
  return a-b
  
def mul(a,b):
  return a*b
  
def div(a, b):
  return a/b


main.py
import arithmetic

print(arithmetic.sum(10, 20))
print(arithmetic.subtract(10, 20))
print(arithmetic.mul(10, 20))
print(arithmetic.div(10, 20))


$ python3 main.py
30
-10
200
0.5

Note
It is not necessary to put all import statements in the beginning of module. You can import whenever required.





Previous                                                 Next                                                 Home