CyberKeeda In Social Media

Python : How to Import Modules


Let's get to know,  what are the various ways to import a module within a python file.

We will take example of one of the famous module named as " MATH  " and a function sqrt (used to calculate the square rootwithin the module.
It provide access to mathematical functions defined by C,  to get to know more about it visit the official link

Here are the various ways we can import it.

Import the whole module.

import math

Usage.
module_name.function_name

import math
x=16
print(math.sqrt(16))

Create alias of the imported module.

In case, if you feel using such a big name of your module or nor relevant to it's behavior, you can create the module's name alias.
Let's take the example of the same math module, i will be creating alias m for it.

import math as m

Usage:

import math as m
x=16
print(m.sqrt(x))

Import only specific function, functions from a particular module.

A particular module consists of lot of functions in it, sometimes, we just need only a particular function out of entire module.
Again let's take the same module as an example.module math contains, a lot of functions within it some  are as below.
sqrt()
ceil()
floor()
pow(x,y)
factorial()
fabs()
fmod(x,y)
sin()
cos()

Now, in case we need only one function sqrt() , here is the way how we only import a function from a module.

from math import sqrt
Usage:

from math import sqrt
x=16
print(sqrt(x))

In case, if we need more then one function.
from math import sqrt, cos, sin
x=16
print(cos(x))

Now, if you just simply don't want to write math every time and want to use all of the functions within the module.
from math import *
x=16
print(cos(x))
print(sqrt(x))
print(sin(x))

No comments:

Post a Comment

Designed By Jackuna