0% found this document useful (0 votes)
2 views19 pages

r23 Python Unit 2

The document covers key programming concepts in Python, including conditional control statements (if, else, elif), loop control statements (for, while, break, continue), and functions and modules. It provides detailed explanations and examples for each concept, illustrating how to implement them in Python. Additionally, it discusses the importance of functions for code organization and reusability, along with the use of docstrings and return statements.
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)
2 views19 pages

r23 Python Unit 2

The document covers key programming concepts in Python, including conditional control statements (if, else, elif), loop control statements (for, while, break, continue), and functions and modules. It provides detailed explanations and examples for each concept, illustrating how to implement them in Python. Additionally, it discusses the importance of functions for code organization and reusability, along with the use of docstrings and return statements.
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

UNI

T-2
Conditional Control Statements: if, else, if- elif-else.
Loop Control Statements: for, while, break & continue Statements.
Functions and Modules: Defining Functions, Parameters and Arguments, Return Values, Scope and Global
Variables, Recursive Functions, standard modules and Packages. Case study1: Generating a Calander

Conditional Control Statements:

Generally algorithms require two important conditional control structures: iteration and selection. Both of
these are supported by Python in various forms. The programmer can choose the statement that is most
useful for the given circumstance

Selection Statement (Decision statements):


Selection statements are used to control the flow of a program by making decisions based on conditions.
Most programming languages provide different versions of this useful construct. In Python, these are
primarily implemented using the if, elif, and else statements. The different types of this statement in python
are described below:

1. Simple if statement (single way selection)


2. if else statement (two way selection)
3. Nested if (if – elif – else statement - multi way selection)
1. Simple if Statemnt: Python has a single way selection construct, i.e simple if statement. Its syntax is
given below. With this statement, if the condition is true, an action is performed. In the case where the
condition is false, processing simply continues on to the next statement after if.

Its syntax is if<condition>:


Statements
Python uses indentation to delimit the blocks of code. Other languages like C use braces to accomplish this
task. However in python this indentation is mandatory, otherwise program will not work.

2. if - else Statement: An if statement can also be followed by an else statement which is optional. An
else statement does not have any condition. Its syntax is given below. The statements in the if block are
executed if the Boolean_Expression is True, otherwise the else block will be executed. The if…else
statement used for two-way decision, that means when we have only two alternatives.

else:

3. Nested Decision Structures (if – elif –else): Actually it is short form of else if statement. When we
place if statement into if - else statement then it becomes nested if statement. The elif word is used for this
statement with the following syntax.

if<condition>:
statements elif
<condition>:
statements
elif<condition>:
statements
else:

Page 1
statement
s It is also has the following syntax: if <condtion>:
if<condition>:
Statements
else:
Statements
else:
Statements
Example-1:
a=10 if(a>10):
print("if body")
else:
print("else body")
Example-2: In python 0=false 1=true
if(1):
print('Hai Ramu')
else:
print('Hai Anu')
Example-3: In python Boolean constants start with uppercase character. if(False):
print ("true body")
else: print ("false
body") Example 4:
x = int(input("Please enter an integer:
")) if x > 0: print ("Positive")
elif x == 0:
print ("Zero")
Example 5:
number = 23 guess = int(input("Enter an integer
: ")) if guess == number: print("Congratulations,
you guessed it.") elif guess < number: print("No,
it is a little higher number")
else: print("No, it is a little lower number")
print("rest of the app")
Loop Control Statement:
In general, statements are executed sequentially, i.e The first statement is executed first, followed by the
second, and so on. There may be a situation when we need to execute a single or block of statements
several number of times. In such situations we can use statements called loop statements.
Therefore a loop statement allows us to execute a statement or group of statements multiple times. The
following diagram illustrates a loop statement.

A loop may be finite or infinite loop. A loop becomes infinite loop if it never ends i.e the loop condition
never becomes FALSE. Such a loop is called an infinite loop. An infinite loop might be useful in

Page 2
client/server programming where the server needs to run continuously so that client programs can
communicate with it as and when required.

Loops in Python: Python programming language provides two types of loops to handle looping
Statements in the programs.

Loop Type Description

while loop Repeats a statement or group of statements while a given condition is TRUE. It
tests the condition before executing theloop body.

for loop Executes a sequence of statements multiple times and abbreviates the code that
manages the loop variable.

nested We can use one or more loop inside any another while, or for loop.
loops

While Loop:

A while loop statement in Python programming language repeatedly executes a single or group of
statements as long as a given condition is true. The syntax of a while loop in Python programming
language is given as

while condition:
Statement(s)
else:
Statement(s)
Here, statement(s) may be a single statement or a block of statements with uniform indent. These
statements will get executed until the condition becomes False.
When this while loop is encountered in a python program, then it first evaluates the condition. If the
condition is true then the statements which intend for it will get executed. After completion of execution of
loop statements, again it will check the condition value. If it is true, then it will continue the next iteration.
Hence the statements are continuously executed as long as condition becomes true. When the condition
becomes false, then statements which intend for else part will get executed. However this else part is
optional. Moreover else block will not be executed if loop is stopped by break statement.

Flow Diagram of while loop:

Page 3
Here, a key point of the while loop is that when the conditionis tested and the result is false for the first
time itself, the loop body will be skipped and else part or the first statement afterthe while loop will be
executed. Example 1: Printing the values 1 to 10 with while loop count = 1 while(count < =10): print
('The count is:', count) count = count + 1
Example 2: Printing Fibonacci series with while loop n=int(input(“Enter n value
for fibonacci series”)) a,b = 0,1 while(a<n):
print(a) a,b = b, a+b
Example 3: Finding GCD of two given values
x,y=input(“Enter two values to find
GCD”) x=int(x) y=int(y) while(y!=0) x,y =
y, x%y print(“GCD value is = “,x)

Example 4: The following example illustrates the combination of an else statement with a while statement
that prints a number as long as it is less than 5, otherwise the else statement gets executed. count=1 while
count < 5: print (count, " is less than 5")
count = count+1
else:
print(count, " is not less than 5")
For Loop:

The for statement in Python has the ability to iterate over the items of any sequence, suchas a list or a
string or tuple.

Syntax: for iterating_var in


sequence:
statement(s)
else:
statement(s)
If a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence is
assigned to the iterating variable iterating_var. Next, the statements block is executed. Each item in the
list is assigned to iterating_var, and the statement(s) block is executed until the entire sequence is
exhausted. However, here also else statement is optional. If the else statement is used with a for loop, the
else statement is executed whenthe loop has exhausted iterating the list.

Flow Diagram:

The range() function:

The built-in function range() is the right function to iterate over a sequence of numbers. It generates the
sequence of numbers within the specified range. So this range(n) generates integers starting with 0 upto n-
1. Its syntax is

Syntax: range([start]:end:[step])

Page 4
It will generate a sequence of integers starts from start value upto end-1 value, each time it generate an
integer by using step value. If we not given start value then it will take 0 as default value for start. In the
same way if we not given the step value then it will tabke 1 as default value for step.

Example 1: range(10) will generate sequence like, 0,1,2,3,4,5,6,7,8,9

Example 2: range(1,10,2) will generate sequence like 1,3,5,7,9

This range() can be used along with for loop as follows:

Example 3: for var in list(range(5)):


print (var,end= ‘ ‘)

This will produce the output as 0 1 2 3 4 Example


4:
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # traversal of List sequence
print ('Current fruit :', fruit)
Iterating by Sequence Index
An alternative way of iterating through each item is by index offset into the sequence itself. Following is a
simple example, fruits = ['banana', 'apple', 'mango'] for index in range(len(fruits)): print ('Current fruit :',
fruits[index])

Example 5: The following example illustrates the combination of an else statement with a for statement
that searches for even number in given list. numbers=[11,33,55,39,55,75,37,21,23,41,13] for num in
numbers: if num%2==0:
print(‘the list contains an even numbers’)
break
else:
print(‘ the list does not contain even number’)
Nested Loops:

Python programming language allows the use of one loop inside another loop. This type of loops are
known as nested loops. The following section shows to illustrate the concept.

Syntax: The syntax for a nested while loop statement in Python programming language is as follows-

while expression:
while expression:
statement(s)
statement(s)
The syntax for a nested for loop statement in Python programming language is as follows
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
A final note on loop nesting is that we can put any type of loop inside any other type of loop. For example
a for loop can be inside a while loop or vice versa.

break, continue and pass Statements:

Page 5
The Loop control statements change the execution from its normal sequence by using these statements.
When the execution leaves a scope, all automatic objects that were created in that scope are destroyed. For
that purpose python supports the following control statements.
For that purpose Python supports the following control statements.

Examples for break statement:

Control Description Syntax


Statement

break Terminates the loop statement and transfers break


statement execution to the statement immediately
following the loop.

continue Causes the loop to skip the remainder of its continue


statement body and immediately retest its condition
prior to reiterating.

pass The pass statement in Python is used when a pass


statement statement is required syntactically but we do
not want any command or code to execute.
Example 1:
for letter in 'Python': if letter == 'h':
break
print ('Current Letter :', letter)
Example 2:
var = 10 while var>0:
print(‘Current value of var: ‘,var)
var=var-1 if var == 5:
break
Example 3: no=int(input('any number: '))
numbers=[11,33,55,39,55,75,37,21,23,41,1
3] for num in numbers:
if num==no: print('number
found in list')
break
else:
print ('number not found in list')
Output: any number: 33 number
found in list any
number: 5 number not
found in list
Examples for continue statement: The continue statement can be used in both while and for
loops. Example 1: for letter in 'Python': if letter == 'h':
continue
print ('Current Letter :', letter)
Example 2:

Page 6
var = 10 while var > 0: var =
var -1 if var == 5: continue
print ('Current variable value :', var) pass Statement:
The pass statement is a null operation; nothing happens when it executes. The pass statement is also
useful in places where our code will eventually go. It is used when a statement is required syntactically.
Example:
for letter in 'Python':
if letter == 'h':
pass
print ('This is pass block')
print ('Current Letter :', letter)
Output:
Current Letter : P
Current Letter : y
Current Letter : t
This is pass
block Current
Letter : h
Current Letter : o
Current Letter : n

Python Functions

• In Python, a function is a group of related statements that performs a specific task.


• Functions help break our program into smaller and modular chunks. As our program growslarger and
larger, functions make it more organized and manageable.
• It avoids repetition and makes the code reusable.

Syntax of Function:

def function_name(parameters):
"""docstring""" statement(s) return

Above shown is a function definition that consists of the following


components.
• Keyword def that marks the start of the function header.
• A function name to uniquely identify the function. Function naming follows the same rules ofwriting
identifiers in Python.
• Parameters (arguments) through which we pass values to a function. They are optional.
• A colon (:) to mark the end of the function header.
• documentation string (docstring) to describe what the function does which is optional.
• One or more valid python statements that make up the function body. Statements must have thesame
indentation level (usually 4 spaces).
• return statement to return a value from the function which is optional.

Example of a function:

def greet(name):

Page 7
“””
This function greets to the
Person passed as parameter
“””
Print(Hello, " + name + ". Good morning!")
To Call function call in Python
A function can’t run by its own. It runs only when it is called. So once we have defined a function, we can
call it by i ts name. Hence to call a function we simply type the function name with appropriate parameters.

>>> greet('Tirumala')
Hello, Tirumala. Good morning!
Docstrings:

• The first string after the function header is called the docstring and is short for documentation string. It is
briefly used to explain what a function does.
• Python docstrings are the string literals that appear after the definition of a method, class, or module also.
• In the above example, we have a docstring immediately below the function header. We generally
use triple quotes so that docstring can extend up to multiple lines.
• We can access these docstrings using the doc attribute.

Example: 1
>>> print(greet. doc )
This function greets to the person passed in as a
parameter Example 2: def square(n):
‘’’Takes in a number n, returns the square of n’’’
return n**2
print(square. doc ) Output:
Takes in a number n, returns the square of n
Example 3: Docstrings for the built-in print() function

print(print. doc ) Output:


print(value, ..., sep=' ', end='\n', file=[Link], flush=False)
Prints the values to a stream, or to [Link] by default.
Optional keyword arguments:

file: a file-like object (stream); defaults to the current


[Link]. sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.

Docstrings for Python Modules:

• The docstrings for Python Modules should list all the available classes, functions, objects and
exceptions that are imported when the module is imported.
• They should also have a one-line summary for each item.
• They are written at the beginning of the Python file.
Example 4: docstrings for the builtin module in Python called
pickle. import pickle print(pickle. doc )

Page 8
The return statement:

• The return statement is used to exit a function and go back to the place from where it was called.
• This statement can contain an expression that gets evaluated and the value is returned.
• If there is no expression in the statement or the return statement itself is not present inside a function,
then the function will return the None object.
Syntax of return: return [expression_list]

Example1:
>>> print(greet("May"))
Output:
Hello, May. Good morning!
None

Example: 2
def absolute_value(num):
"""This function returns the absolute value of the entered number"""
if num >= 0:
return num
else:
return -num
print(absolute_value(2))
print(absolute_value(-4))
Output:
2
4
Types of Functions: Basically, we can divide functions into the following two types:

1. Built-in functions - Python has several functions that are readily available for use. These functionsare
called built-in functions.
Examples: abs(), any(), all(), ascii(), bin(), bool(), callable(), chr(), compile(), classmethod(), delattr(), dir(),
divmod(), staticmethod(), filter(), getattr(), globals(), exec(), hasattr(), hash(), isinstance(), issubclass(),
iter(), locals(), map(), next(), memoryview(), object(), property(), repr(), reversed(), vars(), import (),
super()
2. User-defined functions -
• Functions that we define ourselves to do certain specific task are referred as user-defined functions.
• If we use functions written by others in the form of library, it can be termed as library functions.
• All the other functions that we write on our own fall under user-defined functions. So, our user- defined
function could be a library function to someone else.
Advantages of user-defined functions:

• User-defined functions help to decompose a large program into small segments which makes program
easy to understand, maintain and debug.
• If repeated code occurs in a program. Function can be used to include those codes and executewhen
needed by calling that function.
• Programmars working on large project can divide the workload by making different functions.
Example:
def add_numbers(x,y):
sum = x + y

Page 9
return sum

num1 = 5
num2 = 6
print("The sum is", add_numbers(num1, num2))
Output: The sum is 11

Python Function Arguments: In Python, we can define a function that takes variable number of
arguments.
Example:
def greet(name, msg):
"""This function greets to the person with the provided message"""
print("Hello", name + ', ' + msg)

greet("Titumala", "Good morning!")

Output: Hello Tirumala, Good morning!

• Here, the function greet() has two parameters. Since we have called this function with twoarguments, it
runs smoothly and we do not get any error.
• If we call it with a different number of arguments, the interpreter will show an error message.
• If we call to this function with one and no arguments along with their respective errormessages.

>>> greet("Monica") # only one argument


TypeError: greet() missing 1 required positional argument: 'msg'

>>> greet() # no arguments


TypeError: greet() missing 2 required positional arguments: 'name' and 'msg'

In python, there are three different forms of Function Arguments which have been given below.
1. Default Arguments.
2. Keyword Arguments.
3. Arbitrary Arguments/Variable Length Arguments.

1. Default Arguments:
Function arguments can have default values. We can provide a default value to an argument by using the
assignment operator (=).
Example:
def greet(name, msg="Good morning!"):
print("Hello", name + ', ' + msg)

greet("Tirumala")
greet("CSE", "Welcome to Technical Wing.")

Output:
Hello Tirumala, Good morning!
Hello CSE, Welcome to Technical Wing.

Explanation:

Page 10
• The parameter name does not have a default value and is required (mandatory) during a call.
• The parameter msg has a default value of "Good morning!”. So, it is optional during a call. If a value
is provided, it will overwrite the default value.
• Any number of arguments in a function can have a default value. But once we have a default
argument, all the arguments to its right must also have default values.
• This means to say, non-default arguments cannot follow default arguments. Example:
def greet(msg = "Good morning!", name):

Output: Syntax Error: non-default argument follows default argument.

2. Keyword Arguments:
• Python allows functions to be called using keyword arguments. When we call functions in this
way, the order (position) of the arguments can be changed.
• Following calls to the above function are all valid and produce the same result.
# 2 keyword arguments
greet(name = "TEC", msg = "Good Morning")

# 2 keyword arguments (out of order)


greet(msg = "Good Morning", name = "TEC")

1 positional, 1 keyword argument


greet("TEC", msg = "Good Morning")

Output: Hello TEC, Good Morning


• Having a positional argument after keyword arguments will result in errors.
Example: greet(name="TEC", "Good Morning”)
Output: SyntaxError: non-keyword arg after keyword arg.

3. Arbitrary Arguments / Variable Length Arguments:


• Sometimes, we do not know in advance the number of arguments that will be passed into a
function.
• Python allows us to handle this kind of situation through function calls with an arbitrarynumber of
arguments.
• In the function definition, we use an asterisk (*) before the parameter name to denote this kind of
argument.

Example:
def greet(*names):
# names is a tuple with
arguments for name in names:
print("Hello", name)
greet("Monica", "Lakshmi",
"Sravan", "Jasmin")
Output:
Hello Monica
Hello Lakshmi
HelloSravan
Hello Jasmin
Page 11
Explanation: we have called the function with multiple arguments. These arguments get wrappedup into a
tuple before being passed into the function. Inside the function, we use for loop to retrieve all the
arguments back.

Recursive Function:
• A function that calls itself is known as Recursive Function.
• A physical world example would be to place two parallel mirrors facing each other. Any object in
between them would be reflected recursively.
• The following image shows the working of a recursive function called recurse.

Example:

def factorial(n):
if n == 1
return 1
else
return (n*factorial(n-1))

num = 5
print(“the factorial of “, num,”is”, factorial(num)) output:
the factorial of 5 is 120
This recursive call can be explained in the following steps.

factorial(3) # 1st call with 3

3 * factorial(2) # 2nd call with 2

3 * 2 * factorial(1) # 3rd call with 1

3*2*1 # return from 3rd call as number=1

3*2 # return from 2nd call

6 # return from 1st call

Advantages of Recursion:
1. Recursive functions make the code look clean and elegant.
2. A complex task can be broken down into simpler sub-problems using recursion.
3. Sequence generation is easier with recursion than using some nested iteration.
Disadvantages of Recursion:
1. Sometimes the logic behind recursion is hard to follow through.
2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
3. Recursive functions are hard to debug.

Page 12
Python Anonymous/Lambda Function:
• In Python, an anonymous function is a function that is defined without a name.
• While normal functions are defined using the def keyword in Python, anonymous functions are
definedusing the lambda keyword.
• Hence, anonymous functions are also called lambda functions.
• Lambda functions can have any number of arguments but only one expression. The expression
isevaluated and returned. Lambda functions can be used wherever function objects are required.

Syntax of Lambda Function: lambda arguments: expression

Example:
# Program to show the use of lambda functions
double = lambda x: x * 2
print(double(5))

Output: 10
Use of Lambda Function in python:
• We use lambda functions when we require a nameless function for a short period of time.
• In Python, we generally use it as an argument to a higher-order function (a function that takes in
other functions as arguments). Lambda functions are used along with built-in functions like
filter(), map() etc.

Example use with filter(): The filter() function in Python takes in a function and a list as arguments.

# Program to filter out only the even items from a list


my_list = [1, 5, 4, 6, 8, 11, 3, 12] new_list =
list(filter(lambda x: (x%2 == 0) , my_list))
print(new_list)

Output: [4, 6, 8, 12]

Example use with map(): The map() function in Python takes in a function and a list.

# Program to double each item in a list using map()


my_list = [1, 5, 4, 6, 8, 11, 3, 12] new_list =
list(map(lambda x: x * 2 , my_list))
print(new_list)
Output: [2, 10, 8, 12, 16, 22, 6, 24]

Scope and Lifetime of variables:

• Scope of a variable is the portion of a program where the variable is recognized. Parameters and
variables defined inside a function are not visible from outside the function. Hence, they have a local
scope.
• The lifetime of a variable is the period throughout which the variable exits in the memory. The lifetime
of variables inside a function is as long as the function executes.
• They are destroyed once we return from the function. Hence, a function does not remember the value of
a variable from its previous calls.
Example:
def my_fun():
x = 10

Page 13
print("Value inside function:",x)

x = 20
my_fun()
print("Value outside function:",x)

Output:
Value inside function: 10
Value outside function: 20
Explanation:
• Here, we can see that the value of x is 20 initially. Even though the function my_fun() changed thevalue
of x to 10, it did not affect the value outside the function.
• This is because the variable x inside the function is different (local to the function) from the one
[Link] they have the same names, they are two different variables with different scopes.

Python Global, Local and Nonlocal variables

Global Variables: In Python, a variable declared outside of the function or in global scope is known as a
global variable. This means that a global variable can be accessed inside or outside of the function.
Example 1: Create a Global
Variable x = "global"
def fun():
print("x inside:", x)
fun()
print("x outside:", x) Output:
x inside: global
x outside: global

➢ What if we want to change the value of x inside a function?


Example 2:

x=”global” def
fun():
x=x*2
print(x)
fun()

Output: UnboundLocalError: local variable 'x' referenced before assignment

Explanation: The output shows an error because Python treats x as a local variable and x is also not
definedinside fun(). To make this work, we use the global keyword.

Example 3: Changing Global Variable from inside a Function using global


c = 0 #global c
def add():
global c
c=c+2
print(“inside function”,c)

print("Before In main:", c) add()

Page 14
print("In main:", c)

Output:
Before In main: 0
Inside add(): 2
In main: 2

2. Local Variables: A variable declared inside the function's body or in the local scope is known as a
localvariable.
Example 1: Accessing local variable outside the scope

def fun(): y=
“local”
fun()
print(y)

Output: NameError: name 'y' is not defined

Explanation: The output shows an error because we are trying to access a local variable y in a
global scopewhereas the local variable only works inside fun() or local scope. Example 2: create a
local variable

def fun():
y= “local”
print(y)
fun()

Output: local

Example 3: Global variable and Local variable with same


name x = 5 def fun():
x=10
print(“local x : “,x)

fun()
print(“global x: “,x)

Output:
Local x: 10
Global x: 5
Explanation: In the above code, we used the same name x for both global variable and local variable. We
get adifferent result when we print the same variable because the variable is declared in both scopes, i.e.
the local scope inside fun() and global scope outside fun().

Python Modules

• Modules refer to a file containing Python statements and definitions. We use modules to break down
large programs into small manageable and organized files. Furthermore, modules provide reusability of
code.
• We can define our most used functions in a module and import it, instead of copying their definitions
into different programs.

Page 15
Example: Type the following and save it as [Link].

# Python Module example

def add(a,
b): c=
a+b
return
c
Explanation: Here, we have defined a function add() inside a module named example. The function takes
in two numbers and returns their sum.

How to import modules in Python?

• We can import the definitions inside a module to another module or the interactive interpreter in Python.
• We use the import keyword to do this. To import our previously defined module example, we type the
following in the Python prompt. >>> import example

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:
>>> [Link](4,5.5)
9.5
There are various ways to import modules. They are listed below..

1. Python import statement


2. import with renaming
3. Python from <module name> import statement
4. import all names
1. Python import statement:
• We can import a module using the import statement and access the definitions inside it using the dot
operator as described above.
Example:
import math
print("The value of pi is", [Link])
Output: The value of pi is 3.141592653589793

2. import with renaming:


• We can import a module by renaming it. We have renamed the math module as m. This can save us
typing time in some cases.
• Note: that the name math is not recognized in our scope. Hence, [Link] is invalid, and [Link] is the
correct implementation.
Example:
import math as m
print("The value of pi is", [Link])

3. Python from...import statement:


• We can import specific names from a module without importing the module as a whole. Here, we
imported only the pi attribute from the math module. In such cases, we don't use the dot operator .
Example 1:

Page 16
from math import pi
print("The value of pi is", pi)
Example 2:
We can also import multiple attributes as
>>> from math import pi, e
>>> pi
3.141592653589793
>>> e
2.718281828459045

4. import all names:


• We can import all names(definitions) from a module. we can import all the definitions from
the math module. This includes all names visible in our scope except those beginning with an
underscore(private definitions).
• 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 Package

• We don't usually store all of our files on our computer in the same location. We use a well-
organized hierarchy of directories for easier access.
• Similar files are kept in the same directory, for example, we may keep all the songs in the
"music" directory. Analogous to this, Python has packages for directories and modules for
files.
• As our application program grows larger in size with a lot of modules, we place similar
modules in one package and different modules in different packages. This makes a project
(program) easy to manage and conceptually clear.
• Similarly, as 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.
• Here is an example. Suppose we are developing a game. One possible organization of
packages and modules could be as shown in the figure below.

Page 17
Standard Modules in Python:

Python includes a wide range of standard modules that come bundled with the Python installation. These
modules cover various functionalities such as system access, file I/O, text processing, and more. Below is
a categorized list of some key standard modules in Python:
General Purpose
• sys: Access system-specific parameters and functions.
• os: Interact with the operating system.
• platform: Information about the Python version and platform.
• shutil: High-level file operations like copying and archiving.
• subprocess: Manage subprocesses.

File and Directory Handling


• [Link]: Common pathname manipulations.
• pathlib: Object-oriented filesystem paths.
• tempfile: Create temporary files and directories.
• glob: File pattern matching.
• fnmatch: Unix filename pattern matching.

Data Types and Algorithms


• collections: Specialized container datatypes.
• dataclasses: Create classes for storing data.
• heapq: Heap queue algorithms.
• bisect: Array bisection algorithms.
• array: Efficient arrays of numeric values.
• enum: Define enumerations.

Mathematics and Numbers


• math: Mathematical functions.
• cmath: Complex number operations.
• decimal: Decimal fixed-point and floating-point arithmetic.
• fractions: Rational numbers.
• random: Random number generation.
• statistics: Basic statistical functions.

Date and Time


• datetime: Date and time manipulation.
• time: Time-related functions.
• calendar: General calendar-related functions.

String and Text Processing


• re: Regular expressions.
• string: Common string operations.
• textwrap: Text wrapping and filling.
• unicodedata: Unicode character database.
• codecs: Encoding and decoding data.

File Formats and Compression


• csv: CSV file reading and writing.
• json: JSON encoding and decoding.

Page 18
• [Link]: XML parsing and creation.
• pickle: Serialize Python objects.
• gzip, bz2, zipfile, tarfile: Compression formats.

Internet Protocols and Networking •


[Link]: HTTP protocol client.
• ftplib: FTP protocol client.
• smtplib: SMTP protocol client.
• socket: Low-level networking.
• urllib: URL handling.
Email Handling
• email: Handling email messages.
• mailbox: Manipulate mailboxes.

Development and Debugging


• logging: Flexible logging system.
• traceback: Print or retrieve a stack traceback.
• pdb: Python debugger.
• doctest: Test interactive Python examples.
• unittest: Unit testing framework.

Miscellaneous
• itertools: Iterators for efficient looping.
• functools: Higher-order functions and operations.
• weakref: Weak references to objects.
• types: Dynamic type creation and names.
For a comprehensive list of modules in Python installation, we can run the following command in the
Python interpreter:
help('modules')

Page 19

You might also like