Py18: Module

In python, a file saved with .py extension is called module. So in a module we may define a class, data fields and functions.

To use functions defined in another module, in the current module, we have to import. The module is included into current module by using the import keyword.

import moduleName

We can import more than one module. To do that each module is specified using its own import statement.

import moduleName1
import moduleName2
import moduleName3

Once a module is imported, we can use the functions defined in that module by calling it.

import moduleName

moduleName.functionName()

For example, we import the math module, and use the pow() function to find the power a number.

import math

ans = math.pow(2,3)

print("2 to the power of 3 is", ans)

Output

2 to the power of 3 is 8.0

Module alias

After importing a module, we use the module name every time we want to call a function. In python, we may give an alias name for the module. This is a helpful when the name of the module is hard to spell or too long.

import moduleName as aliasName

For example, we give 'm' as the alias name for math module. We call the pow() function using the alias. The output is same as above.

import math as m

ans = m.pow(2,3)

print("2 to the power of 3 is", ans)

Importing function

To import specific function from module, we need to use from keyword to specify which module and import keyword to specify the function name. Doing like this we don't have to use module name when calling the function.

from moduleName import functionName

For example, we want to import the pow() function from the math module.

from math import pow

ans = pow(2,3)

print("2 to the power of 3 is", ans)

Function alias

Like module, we also can give an alias name for the function

from moduleName import functionName as aliasName

For example, we import pow() function from math module and give 'p' as the alias name

from math import pow as p

ans = p(2,3)

print("2 to the power of 3 is", ans)

Importing multiple function

Most of the time we want to import more than one function from a module. We could import functions one by one.

from moduleName import functionName1
from moduleName import functionName2
from moduleName import functionName3

or, list out functions using comma

from moduleName import function1, function2, function3

or, use an "*" to import multiple functions all at once

from moduleName import *

For example, we import all the functions from math module.

from math import *

ans = pow(2,3)
print("2 to the power of 3 is", ans)

ans = sqrt(49)
print("Square root of 49 is", ans)

ans = ceil(2.67)
print("Ceiling value of 2.67 is", ans)

Output

2 to the power of 3 is 8.0
Square root of 49 is 7.0
Ceiling value of 2.67 is 3

The sqrt() function returns the square root of the number and ceil() function give the round up value of nearest integer.

Comments

Popular posts from this blog

Drawing Simple Pie Chart

VB.net connecting to SQL Server

VB.net