r23 Python Unit 2
r23 Python Unit 2
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
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
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.
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.
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.
Flow Diagram:
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 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.
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.
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
Syntax of Function:
def function_name(parameters):
"""docstring""" statement(s) return
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
• 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)
• 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.
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):
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")
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.
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.
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.
Example use with map(): The map() function in Python takes in a function and a list.
• 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.
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
x=”global” def
fun():
x=x*2
print(x)
fun()
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.
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)
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
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].
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.
• 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..
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
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.
Page 18
• [Link]: XML parsing and creation.
• pickle: Serialize Python objects.
• gzip, bz2, zipfile, tarfile: Compression formats.
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