[go: up one dir, main page]

0% found this document useful (0 votes)
98 views7 pages

11.importing Blocks and Code Modules: Import Statement

The document discusses importing modules in Python. It covers the import, from...import, and from...import * statements. The import statement imports a module and creates a reference to it. from...import imports specific objects from a module. from...import * imports all public objects from a module. Examples are provided of importing functions and modules. The dir() function returns the names defined in a module. The document also provides examples of generating random numbers in a range and importing functions to perform calculations.

Uploaded by

Sandeep Reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
98 views7 pages

11.importing Blocks and Code Modules: Import Statement

The document discusses importing modules in Python. It covers the import, from...import, and from...import * statements. The import statement imports a module and creates a reference to it. from...import imports specific objects from a module. from...import * imports all public objects from a module. Examples are provided of importing functions and modules. The dir() function returns the names defined in a module. The document also provides examples of generating random numbers in a range and importing functions to perform calculations.

Uploaded by

Sandeep Reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

11.

Importing Blocks and Code Modules


Objective

Import statement

from...import statement

from...import * statement

11.1

Import Statement

11.2

Problem statement

11.3

Practise Problems

11.1. Import Statement


The basic purpose of the import statement is to:

Identify one of the following items

An ordinary module

A package

A module within a package

An attribute of a module or package

Bind information about this external item to a variable local to the current module.
Code in the current module will then use this local-module variable to interact with the external item
Python provides at least three different ways to import modules. You can use the import statement,
the from statement, or the built-in__import__function.
These are:

import x -- imports the module X, and creates a reference to that module in the current
namespace. x may be a module or package

from x import b imports the module X, and creates references in the current namespace to
the given objects. Or in other words, you can now use a in your program. x may be a module or
package; b can be a contained module or object (class, function etc.)

From x import * - imports the module X, and creates references in the current namespace to
all public objects defined by that module

Finally, X = __import__(X) works like import X, with the difference that you

1) pass the module name as a string,


and 2) explicitly assign it to a variable in your current namespace.
Import statement
You can use any Python source file as a module by executing an import statement in some other
Python source file. The import has the following syntax:
import module1[, module2[,... moduleN]

When the interpreter encounters an import statement, it imports the module if the module is present
in the search path. A search path is a list of directories that the interpreter searches before importing
a module. For example, to import the module hello.py, you need to put the following command at the
top of the script:
Here's an example of a simple module, hello..py
#!/usr/bin/python
def print_func( par ):
print "Hello : ", par
return
now if we want to use this in another program then we can just write as below:
# Import module support
import support
# Now you can call defined function that module as follows
support.print_func("Sarah")
When the above code is executed, it produces the following result:
Hello : Sarah
A module is loaded only once, regardless of the number of times it is imported. This prevents the
module execution from happening over and over again if multiple imports occur.
Example:
vi mod.py
#!/usr/bin/python
def func():
print "This is sample function"
vi mod1.py
#!/usr/bin/python
#Importing the module mod.py

import mod
mod.func()
After execution of mod1.py as python mod1.py the output will be:
This is sample function
From...import statement
Python's from statement lets you import specific attributes from a module into the current
namespace. The from...import has the following syntax:
from modname import name1[, name2[, ... nameN]]
For example, to import the function fibonacci from the module fib, use the following statement:
from fib import fibonacci
This statement does not import the entire module fib into the current namespace; it just introduces
the item fibonacci from the module fib into the global symbol table of the importing module.
Example:
vi mod2.py
#!/usr/bin/python
from mod import func
func()
After execution of mod2.py as python mod2.py the output will be:
This is sample function
From...import * statement
It is also possible to import all names from a module into the current namespace by using the
following import statement:
from modname import *
This provides an easy way to import all the items from a module into the current namespace.
Example:
vi mod3.py

from mod import *


func()
It will import every function from module into the current namespace.
dir() function:
The dir() built-in function returns a sorted list of strings containing the names defined by a module.
The list contains the names of all the modules, variables and functions that are defined in a module.
Following is a simple example:
#!/usr/bin/python
# Import built-in module math
import math
content = dir(math)
print content;
When the above code is executed, it produces the following result:
['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan',
'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp',
'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log',
'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh',
'sqrt', 'tan', 'tanh']
Here, the special string variable __name__ is the module's name, and __file__ is the filename from
which the module was loaded.

11.2. Problem statement


Find whether random function generated is in range of 25 or 50 or 75 or 100

Solution
#!/usr/bin/python
import random
i=random.randrange(0,100) #random number generated will be from 0 to 100.
print " random number is "
print i
if i<25:
print " This value is less than 25"
elif i<50:
print " This value is less than 50 greater than 25"
elif i<75:
print " This value is less than 75 grater than 50"
else:
print " This value is less than 100 greater than 75"

Chapter 11:
Importing blocks and code modules

Write a function to find the area of square.Import the module area and find volume of the
cube with the area.(height shouldn't be defined).

Write a program with three functions add,subtract and multiply.Import add and multiply
into a program which displays results of those functions.
Generate a random value from x to y.Here take x and y from user.

Answers:
1.
#!/usr/bin/python
# sample.py file
def area(side):
return (side*side)
# sample2.py file

#!/usr/bin/python
import sample
def volume(side):
try:
return ((sample.area(side))**(3.0/2))
except:
print "ERROR:"
# print volume(6) if you remove comment it prints 216.0
2.
#!/usr/bin/python
# file s1
def add(a,b):
return (a+b)
def sub(a,b):
return (a-b)
def mul(a,b):
return (a*b)
# file s2
#!/usr/bin/python
from s1 import add,mul
def display(a,b):
print ("addition of ",a,"and",b,":",add(a,b))
print ("multiplication of ",a,"and",b,":",mul(a,b))
display(2,3)

3.
#!/usr/bin/python
import random
x=input('enter the value where range starts')
y=input('enter the value where range ends')
z=random.randrange(x,y)
print z

You might also like