R20-N-Python Unit 3 - Chandu
R20-N-Python Unit 3 - Chandu
R20-N-Python Unit 3 - Chandu
PYTHON PROGRAMMING
UNIT -III
List and Dictionaries: Lists, Defining Simple Functions, Dictionaries
Design with Function: Functions as Abstraction Mechanisms, Problem
Solving with Top Down Design, Design with Recursive Functions, Case Study
Gathering Information from a File System, Managing a Program’s Namespace,
Higher Order Function.
Modules: Modules, Standard Modules, Packages..
There are four collection data types in the Python programming language:
• List is a collection which is ordered and changeable. Allows duplicate members.
• Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
• Set is a collection which is unordered and un indexed. No duplicate members.
• Dictionary is a collection which is unordered, changeable and indexed. No duplicate
members.
List:
A list is a sequence of values (similar to an array in other programming languages but more
versatile). The values in a list are called items or sometimes elements.
The important properties of Python lists are as follows:
Lists are ordered – Lists remember the order of items inserted.
Accessed by index – Items in a list can be accessed using an index.
Lists can contain any sort of object – It can be numbers, strings, tuples and even other
lists.
Lists are changeable (mutable) – You can change a list in-place, add new items, and
delete or update existing items.
Create a List
There are several ways to create a new list; the simplest is to enclose the values in square
brackets []
# A list of integers
L = [1, 2, 3]
# A list of strings
L = ['red', 'green', 'blue']
The items of a list don’t have to be the same type. The following list contains an integer, a string,
a float, a complex number, and a boolean.
# A list of mixed datatypes
L = [ 1, 'abc', 1.23, (3+4j), True]
A list containing zero items is called an empty list and you can create one with empty brackets []
# An empty list
L = []
There is one more way to create a list based on existing list, called List comprehension.
Replacing an element of the list can be done with the help of assignment statement
List are mutable, meaning, their elements can be changed unlike string or tuple.
We can use assignment operator (=) to change an item or a range of items.
# change the 1st item
>>> li = [10,20,30,40,50,60]
>>> li
[10, 20, 30, 40, 50, 60]
>>> li[0]=100
>>> li
[100, 20, 30, 40, 50, 60]
Basic List Operations
Lists respond to the + and * operators much like strings; they mean concatenation and repetition
here too, except that the result is a new list, not a string.
In fact, lists respond to all of the general sequence operations we used on strings in the prior
chapter.
Python Expression Results Description
print(my_list[:-5])
# elements 6th to end
print(my_list[5:])
# elements beginning to end
print(my_list[:])
Output
['o', 'g', 'r']
['p', 'r', 'o', 'g']
['a', 'm', 'i', 'z']
['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z']
Slicing can be best visualized by considering the index to be between the elements as shown
below. So if we want to access a range, we need two indices that will slice that portion from the
list.
thislist.clear()
print(thislist)
Output: [ ]
Copy a List:
A list can be copied using the = operator. For example,
old_list = [1, 2, 3]
new_list = old_list
The problem with copying lists in this way is that if you modify new_list, old_list is also
modified. It is because the new list is referencing or pointing to the same old_list object.
You cannot copy a list simply by typing list2 = list1, because: list2 will only be
a reference to list1, and changes made in list1 will automatically also be made in list2.
There are three ways to make a copy, one way is to use the built-in List method copy().
1. Make a copy of a list with the copy( ) method.
Ex: thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
Output: apple banana cherry
2. Another way to make a copy is to use the built-in method list( ). Make a copy of a list with
the list( ) method.
Ex: thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)
Output: apple banana cherry
3.Using slicing technique
This is the easiest and the fastest way to clone a list. This method is considered when we
want to modify a list and also keep a copy of the original. In this we make a copy of the list
itself, along with the reference. This process is also called cloning.
# shallow copy using the slicing syntax
# mixed list
list = ['cat', 0, 6.7]
# copying a list using slicing
new_list = list[:]
# Adding an element to the new list
new_list.append('dog')
# Printing new and old list
print('Old List:', list)
print('New List:', new_list)
Output
Old List: ['cat', 0, 6.7]
Join Two LISTS: There are several ways to join, or concatenate, two or more lists in Python.
1. One of the easiest ways are by using the + operator.
Ex: list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
Output: ‘a’ ‘b’ ‘c’ 1 2 3
2. Another way to join two lists are by appending all the items from list2 into list1, one by one.
Ex: Append list2 into list1.
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
for x in list2:
list1.append(x)
print(list1)
Output: [‘a’ ‘b’ ‘c’ 1 2 3]
3. We can use the extend() method, which purpose is to add elements from one list to another
list. Use
the extend() method to add list2 at the end of list1.
Ex: list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
Output: [‘a’ ‘b’ ‘c’ 1 2 3]
The List() Constructor: It is also possible to use the list() constructor to make a new list.
Using the list() constructor to make a List.
Ex: thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
print(thislist)
Output: [‘apple’ ‘banana’ ‘cherry’]
Python Nested List
A list can contain any sort object, even another list (sublist), which in turn can contain sublists
themselves, and so on. This is known as nested list.
You can use them to arrange data into hierarchical structures.
Create a Nested List
A nested list is created by placing a comma-separated sequence of sublists.
L = ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', 'h']
Access Nested List Items by Index
You can access individual items in a nested list using multiple indexes.
The indexes for the items in a nested list are illustrated as below:
print(L[2])
# Prints ['cc', 'dd', ['eee', 'fff']]
print(L[2][2])
# Prints ['eee', 'fff']
print(L[2][2][0])
# Prints eee
print(L[-3][-1])
#Prints ['eee', 'fff']
print(L[-3][-1][-2])
# Prints eee
Python List Methods
Methods that are available with list objects in Python programming are tabulated below.
They are accessed as list.method(). Some of the methods have already been used above.
Python List Methods
# Output: 2
print(my_list.count(8))
my_list.sort()
# Output: [0, 1, 3, 4, 6, 8, 8]
print(my_list)
my_list.reverse()
# Output: [8, 8, 6, 4, 3, 1, 0]
print(my_list)
Output
1
2
[0, 1, 3, 4, 6, 8, 8]
[8, 8, 6, 4, 3, 1, 0]
List comprehensions
A Python list comprehension is a method for constructing a list from a list, a range, or other
iterable structure. List comprehensions are frequently used to extract data from other lists or to
generate new data from an existing data list.
List comprehension is an elegant and concise way to create a new list from an existing list in
Python. A list comprehension consists of an expression followed by for statement inside square
brackets.
Syntax of List Comprehension
list_variable = [expression for item in collection]
ex1: Here is an example to make a list with each item being increasing power of 2.
pow2 = [2 ** x for x in range(10)]
print(pow2)
Output
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
This code is equivalent to:
pow2 = []
for x in range(10):
pow2.append(2 ** x)
The first expression generates elements in the list followed by a for loop over some collection of
data which would evaluate the expression for every item in the collection.
V = [2**i for i in range(13)]
V
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096]
Dictionaries
Dictionaries are Python’s implementation of a data structure that is more generally known as
an associative array.
A dictionary consists of a collection of key-value pairs. Each key-value pair maps the key to
its associated value.
Python dictionary is an unordered collection of items. Each item of a dictionary has a
key/value pair.
Dictionaries are optimized to retrieve values when the key is known.
# empty dictionary
my_dict = {}
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
If we use the square brackets [], KeyError is raised in case a key is not found in the dictionary.
On the other hand, the get() method returns None if the key is not found.
Example:
my_dict = {'name': 'Jack', 'age': 26}
print(my_dict['name'])
print(my_dict.get('age'))
# Trying to access keys which doesn't exist throws error None
print(my_dict.get('address'))
print(my_dict['address'])
Output
Jack
26
None
Traceback (most recent call last):
File "<string>", line 15, in <module>
print(my_dict['address'])
KeyError: 'address'
Changing and Adding Dictionary elements
Dictionaries are mutable. We can add new items or change the value of existing items using an
assignment operator.
If the key is already present, then the existing value gets updated. In case the key is not
present, a new (key: value) pair is added to the dictionary.
# Changing and adding Dictionary Elements
my_dict = {'name': 'Jack', 'age': 26}
# update value
my_dict['age'] = 27
print(my_dict)
# add item
my_dict['address'] = 'Downtown'
print(my_dict)
Output
{'name': 'Jack', 'age': 27}
{'name': 'Jack', 'age': 27, 'address': 'Downtown'}
>>> phonebook
{'Amit': '9948911111', 'Arun': '8899776655', 'Amol': '1212121211'}
To delete any entry from a dictionary. The del operator is used to remove a key and its
associated value. If a key is in a dictionary then it is removed otherwise Python raises an error.
The syntax used to remove an element from a dictionary is
del dictionary_name[key] Example:
>>> phonebook
{'Amit': '9948911111', 'Arun': '8899776655', 'Amol': '1212121211'}
>>> del phonebook["Amol"]
>>> phonebook
{'Amit': '9948911111', 'Arun': '8899776655'}
Accessing and replacing values
Accessing of value associated key from the dictionary can be done using the subscript [ ]
operator. Dictionary_Name[key]
>>> phonebook
{'Amit': '9948911111', 'Arun': '8899776655'}
>>>
Iterating Through a Dictionary or Traversing Dictionaries
The for loop is used to traverse all the keys and values of a dictionary. A variable of the for loop
is bound to each key in an unspecified order. It means it retrieves the key and its value in any
order.
Example:
Grades={"Ramesh":"A","Viren":"B","Kumar":"C"}
for key in Grades:
print(key,":",str(Grades[key]))
Output:
Ramesh : A
Viren : B
Kumar : C
If you use a dictionary in a for loop, it traverses the keys of the dictionary by default.
D = {'name': 'Bob', 'age': 25, 'job': 'Dev'}
for x in D:
print(x)
output:
name age job
There are three dictionary methods that return all of the dictionary’s keys, values and key-value
pairs: keys(), values(), and items(). These methods are useful in loops that need to step through
dictionary entries one by one.
All the three methods return iterable object. If you want a true list from these methods, wrap
them in a list() function.
D = {'name': 'Bob', 'age': 25, 'job': 'Dev'}
# get all keys
print(D.keys())
# get all values
print(list(D.values()))
# get all pairs
print(list(D.items()))
output:
dict_keys(['name', 'age', 'job'])
['Bob', 25, 'Dev']
[('name', 'Bob'), ('age', 25), ('job', 'Dev')]
# Prints False
Python Dictionary Comprehension
Dictionary comprehension is an elegant and concise way to create a new dictionary from an
iterable in Python.
Dictionary comprehension consists of an expression pair (key: value) followed by
a for statement inside curly braces {}.
Here is an example to make a dictionary with each item being a pair of a number and its square.
# Dictionary Comprehension
squares = {x: x*x for x in range(6)}
print(squares)
Output
squares = {}
for x in range(6):
squares[x] = x*x
print(squares)
Output
Here, the nested_dict is a nested dictionary with the dictionary dictA and dictB. They are two
dictionary each having own key and value.
Create a Nested Dictionary
A nested dictionary is created the same way a normal dictionary is created. The only difference
is that each value is another dictionary.
D = {'emp1': {'name': 'Bob', 'job': 'Mgr'},
'emp2': {'name': 'Kim', 'job': 'Dev'},
'emp3': {'name': 'Sam', 'job': 'Dev'}}
The dict() Constructor
There are several ways to create a nested dictionary using a type constructor called dict().
To create a nested dictionary, simply pass dictionary key:value pair as keyword arguments to
dict() Constructor.
D = dict(emp1 = {'name': 'Bob', 'job': 'Mgr'},
emp2 = {'name': 'Kim', 'job': 'Dev'},
emp3 = {'name': 'Sam', 'job': 'Dev'})
print(D)
output:
{'emp1': {'name': 'Bob', 'job': 'Mgr'}, 'emp2': {'name': 'Kim', 'job': 'Dev'},
'emp3': {'name': 'Sam', 'job': 'Dev'}}
You can use dict() function along with the zip() function, to combine separate lists of keys and
values obtained dynamically at runtime.
IDs = ['emp1','emp2','emp3']
EmpInfo = [{'name': 'Bob', 'job': 'Mgr'},
print(D)
output:
{'emp1': {'name': 'Bob', 'job': 'Mgr'}, 'emp2': {'name': 'Kim', 'job': 'Dev'},
'emp3': {'name': 'Sam', 'job': 'Dev'}}
Python Function
Functions are the most important aspect of an application.
A function can be defined as the organized block of reusable code, which can be called
whenever required.
A function in any programming language is a single comprehensive unit (self-contained
block) containing a block of code that performs a specific task.
Python allows us to divide a large program into the basic building blocks known as a
function.
A function can be called multiple times to provide reusability and modularity to the
Python program.
The Function helps to programmer to break the program into the smaller part. It
organizes the code very effectively and avoids the repetition of the code. As the program
grows, function makes the program more organized.
Python provide us various inbuilt functions like range() or print(). Although, the user can
create its functions, which can be called user-defined functions.
Functions as Abstraction Mechanisms
Abstraction is used to hide the internal functionality of the function from the users. The
users only interact with the basic implementation of the function, but inner working is
hidden. User is familiar with that "what function does" but they don't know "how it
does."
In Python, an abstraction is used to hide the irrelevant data/class in order to reduce the
complexity. It also enhances the application efficiency. In Python, abstraction can be
achieved by using abstract classes and interfaces.
Advantages:
Breaking problems into parts help us to identify what needs to be done.
At each step of refinement, new parts will become less complex and therefore easier to
solve.
Parts of the solution may turn out to be reusable.
Breaking problems into parts allows more than one person to solve the problem
Function Calling
In Python, after the function is created, we can call it from another function. A function must be
defined before the function call; otherwise, the Python interpreter gives an error. To call the
function, use the function name followed by the parentheses.
Consider the following example of a simple example that prints the message "Hello World".
#function definition
def hello_world():
print("hello world")
# function calling
hello_world()
Output:
hello world
Docstring
The first string after the function is called the Document string or Docstring in short. These
strings are used to describe the functionality of the function. The use of docstring in functions is
optional but it is considered a good practice.
We can access the docstring by __doc__ attribute. For example function_name.__doc__.
Note: The doc attribute has two underscores(__) before and after. Using single underscore (_)
will raise an error.
Here is the example to show how we can access the docstring in Python functions.
def Hello():
""" Hello World """
print ('Hi')
print ("The doctsring of the function Hello is: "+ Hello.__doc__)
Output:
This script will generate following output.
The docstring of the function Hello is: Hello World
The return statement
The return statement is used at the end of the function and returns the result of the function. It
terminates the function execution and transfers the result where the function is called. The return
statement cannot be used outside of the function.
Syntax
return [expression_list]
It can contain the expression which gets evaluated and value is returned to the caller function. If
the return statement has no expression or does not exist itself in the function then it returns
the None object.
Example 1
# Defining function
def sum():
a = 10
b = 20
c = a+b
return c
# calling sum() function in print statement
print("The sum is:",sum())
Output:
The sum is: 30
In the above code, we have defined the function named sum, and it has a statement c =
a+b, which computes the given values, and the result is returned by the return statement to the
caller function.
Example 2 Creating function without return statement
# Defining function
def sum():
a = 10
b = 20
c = a+b
# calling sum() function in print statement
print(sum())
Output:None
In the above code, we have defined the same function without the return statement as we can see
that the sum() function returned the None object to the caller function.
Arguments in function
The arguments are types of information which can be passed into the function. The arguments
are specified in the parentheses. We can pass any number of arguments, but they must be
separate them with a comma.
Consider the following example, which contains a function that accepts a string as the argument.
Example 1
#defining the function
def func (name):
print("Hi ",name)
#calling the function
func("Devansh")
Output:
Hi Devansh
Hi Devansh
Example 2
#Python function to calculate the sum of two variables
#defining the function
def sum (a,b):
return a+b;
#taking values from the user
a = int(input("Enter a: "))
b = int(input("Enter b: "))
Types of arguments
.A Python Function can have two types of Arguments / Parameters, First is Actual
Arguments and Second is Formal Arguments.
Formal arguments are identifiers used in the function definition to represent
corresponding actual arguments.
Actual arguments are values(or variables)/expressions that are used inside the
parentheses of a function call.
Above definition and terminology of Formal/Actual arguments is same across different
programming languages.
The terms parameter and argument can be used for the same thing: information that are
passed into a function.
From a function's perspective:
A parameter is the variable listed inside the parentheses in the function definition.
An argument is the value that is sent to the function when it is called.
There may be several types of arguments which can be passed at the time of function call
Formal parameters :are the variables defined by the function that receives values when the
function is called. According to the above program, the values 2 and 3 are passed to the function
addition. In the addition function, there are two variables called a and b. The value 2 is copied
into variable a, and value 3 is copied into variable b. The variable a and b are not the actual
parameters. They are copies of the actual parameters. They are known as formal parameters.
These variables are only accessible within the method. After printing the addition of two
numbers, the control is returned back to the main program.
Keyword arguments
Keyword arguments are related to the function calls. When you use keyword arguments in a
function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python interpreter is
able to use the keywords provided to match the values with parameters. You can also make
keyword calls to the printme() function in the following ways −
Live Demo
#!/usr/bin/python
Default arguments
A default argument is an argument that assumes a default value if a value is not provided in the
function call for that argument. The following example gives an idea on default arguments, it
prints default age if it is not passed −
Live Demo
# Function definition is here
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print ("Name: ", name)
print( "Age ", age)
return;
Example2
def printme(*names):
print("type of passed argument is ",type(names))
print("printing the passed arguments...")
for name in names:
print(name)
printme("john","David","smith","nick")
printme ( 70, 60, 50 )
Output:
type of passed argument is <class 'tuple'>
printing the passed arguments...
john
David
smith
nick
70
60
50
In the above code, we passed *names as variable-length argument. We called the function and
passed values which are treated as tuple internally. The tuple is an iterable sequence the same as
the list. To print the given values, we iterated *arg names using for loop.
Recursive Function:
• A function that calls itself is known as Recursive Function. Python Recursive
Function: Introduction
Recursion means iteration. A function is called recursive, if the body of function calls the
function itself until the condition for recursion is true. Thus, a Python recursive function has a
termination condition.
Why does a recursive function in Python has termination condition?
Well, the simple answer is to prevent the function from infinite recursion.
When a function body calls itself with any condition, this can go on forever resulting an infinite
loop or recursion. This termination condition is also called base condition.
Is there any special syntax for recursive functions?
The answer is NO.
In Python, there is no syntactic difference between functions and recursive functions. There is
only a logical difference.
Advantages of Python Recursion
1. Slow.
2. Logical but difficult to trace and debug.
3. Requires extra storage space. For every recursive calls separate memory is allocated for
the variables.
4. Recursive functions often throw a Stack Overflow Exception when processing or
operations are too large.
Python Recursion: Example
Let’s get an insight of Python recursion with an example to find the factorial of 3.
3! = 3 * 2! = 3 * (2 * 1!) = 3 * 2 * 1
This is how a factorial is calculated. Let’s implement this same logic into a program.
#recursive function to calculate factorial
def fact(n):
""" Function to find factorial """
if n == 1:
return 1
else:
return (n * fact(n-1))
Lambda functions can have any number of arguments but only one expression. The expression is
evaluated and returned. Lambda functions can be used wherever function objects are required.
print(double(5))
Output
10
In the above program, lambda x: x * 2 is the lambda function. Here x is the argument and x * 2 is
the expression that gets evaluated and returned.
This function has no name. It returns a function object which is assigned to the identifier double.
We can now call it as a normal function. The statement
double = lambda x: x * 2
def double(x):
return x * 2
These functions are called anonymous because they are not declared in the standard manner by
using the def keyword. You can use the lambda keyword to create small anonymous functions.
Lambda forms can take any number of arguments but return just one value in the form of
an expression. They cannot contain commands or multiple expressions.
An anonymous function cannot be a direct call to print because lambda requires an
expression
Lambda functions have their own local namespace and cannot access variables other
than those in their parameter list and those in the global namespace.
Although it appears that lambda's are a one-line version of a function, they are not
equivalent to inline statements in C or C++, whose purpose is by passing function stack
allocation during invocation for performance reasons.
Syntax
The syntax of lambda functions contains only a single statement, which is as follows −
lambda [arg1 [,arg2,.....argn]]:expression
Following is the example to show how lambda form of function works −
Live Demo
#!/usr/bin/python
Here, both refer to the same object 2, so they have the same id(). Let's make things a little more
interesting.
# Note: You may get different values for the id
a=2
print('id(a) =', id(a))
a = a+1
print('id(a) =', id(a))
b=2
print('id(b) =', id(b))
print('id(2) =', id(2))
Output
id(a) = 9302208
id(a) = 9302240
id(3) = 9302240
id(b) = 9302208
id(2) = 9302208
What is happening in the above sequence of steps? Let's use a diagram to explain this:
def inner_function():
a = 30
print('a =', a)
inner_function()
print('a =', a)
a = 10
outer_function()
print('a =', a)
the output of this program is
a = 30
a = 20
a = 10
Higher-Order Function in Python
A function will be called a Higher Order Function when it contains the other function in the form
of the parameter and returns it as an output. We will call the Higher-Order Function to those
function which works with the other function. Python also supports the Higher-Order Function.
Properties of the Higher-Order Function
1. The function will work as an instance of the object type.
2. In the Higher-Order Function, we can easily store the function in the form of the variable.
3. In the Higher-Order Function, a function can contain another function as a parameter.
4. In the higher-order function, a function can also return the function.
5. We can store these functions in the data structure in the hash table, lists etc.
Functions as object
In Python, programming language function can be assigned as a variable. Here function will not
be called; instead, the reference of the function will be created.
# Here is the Python program to define the functions
# In Python, the function can be treated as objects
def call(text):
return text.upper()
print(call('Hello'))
print(yell('Hello'))
The output of the above program will look like, as shown below:
HELLO
HELLO
In the above example, a function object referenced by a call creates a second name which is, yell.
Pass function as an argument to the other function
Functions are known as Python; therefore, we can pass them as an argument to other functions.
The below example shows us how we can create the greet function, which contains the function
as an argument.
# Python program to create the functions
# function contained the other function as an argument
def Shout(text):
return text.upper()
def whispered(text):
return text.lower()
def greets(func):
# storing the function in a variable
greeting = func(" function created \ and
passed as an argument.")
print(greeting)
greet(Shout)
greet(whisper)
The output of the above program will look like, as shown below:
FUNCTION CREATED\ AND PASSED AS AN ARGUMENT.
Function created \ and passed as an argument
Returning Function
Functions are known as objects; we can return a function from another function. In the below
example, the create_address function returns the address function.
# Python program to define the functions
# Functions can return another function
def create_address(z):
def address(c):
return z + c
return address
add_15 = create_address(15)
print(add_15(10))
The output of the above program will look like, as shown below:
25
Decorators
For the higher-order functions, decorators are used in Python. We can modify the behavior of the
class or the function by using the decorators. The decorator wraps another function to extend the
wrapped function's behavior without modifying the function. Decorators contain the functions as
an argument into another function and then called the decorators inside the wrapper function.
The below example shows us how we can write the higher order function in python.
def twiced(function):
return lambda x: function(function(x))
def f(x):
return x + 3
g = twiced(f)
print g(7)
The result of the above program will look like as shown below:
13
Python Modules
A module is a file containing Python definitions and statements. A module can define functions,
classes, and variables. A module can also include runnable code. Grouping related code into a
module makes the code easier to understand and use. It also makes the code logically organized.
We can define our most used functions in a module and import it, instead of copying their
definitions into different programs.
Explanation: Here, we have defined a function add() inside a module named example. The
function takes in two numbers and returns their sum.
We use the import keyword to do this. To import our previously defined module example, we
type thefollowing in the Python prompt.
This does not import the names of the functions defined in example directly in the current
symbol table. It only imports the module name example there. Using the module name we can
access the function using the dot . operator.
Example:
>>> example.add(4,5.5)
9.5
Python has lots of standard modules. These files are in the Libdirectory inside the location
where you installed Python.
There are various ways to import modules. They are listed below..
Python import statement
import with renaming
Python from...import statement
import all names
Example:
import math
print("The value of pi is", math.pi)
Output:
The value of pi is 3.141592653589793
Example:
import math as m
print("The value of pi is", m.pi)
Example:1
from math import pi print("The value of pi is", pi)
Example:2
Importing everything with the asterisk (*) symbol is not a good programming practice. This can
lead to duplicate definitions for an identifier. It also hampers the readability of our code.
Example:
from math import *
print("The value of pi is", pi)
Python packages
Packages are a way of structuring many packages and modules which helps in a well-organized
hierarchy of data set, making the directories and modules easy to access. Just like there are
different drives and folders in an OS to help us store files, similarly packages help us in storing
other sub-packages and modules, so that it can be used by the user when necessary.
The packages in python facilitate the developer with the application development environment
by providing a hierarchical directory structure where a package contains sub-packages, modules,
and sub-modules. The packages are used to categorize the application level code efficiently.
a directory can contain subdirectories and files, a Python package can have sub-packages and
modules.
A directory must contain a file named init .py in order for Python to consider it as a package.
This file can be left empty but we generally place the initialization code for that package in this
file
Let's create a package named Employees in your home directory. Consider the following steps.
2. Create a python source file with name ITEmployees.py on the path /home/Employees.
ITEmployees.py
def getITNames():
List = ["John", "David", "Nick", "Martin"]
return List;
3. Similarly, create one more python file with name BPOEmployees.py and create a function
getBPONames().
4. Now, the directory Employees which we have created in the first step contains two python
modules. To make this directory a package, we need to include one more file here, that is
__init__.py which contains the import statements of the modules defined in this directory.
__init__.py
from ITEmployees import getITNames
from BPOEmployees import getBPONames
5. Now, the directory Employees has become the package containing two python modules. Here
we must notice that we must have to create __init__.py inside a directory to convert this
directory to a package.
6. To use the modules defined inside the package Employees, we must have to import this in our
python source file. Let's create a simple python source file at our home directory (/home) which
uses the modules defined in this package.
Test.py
import Employees
print(Employees.getNames())
Output:
['John', 'David', 'Nick', 'Martin']
We can have sub-packages inside the packages. We can nest the packages up to any level
depending upon the application requirements.
The following image shows the directory structure of an application Library management system
which contains three sub-packages as Admin, Librarian, and Student. The sub-packages contain
the python modules.
---------------------******--------------------------------