Unit-2 Python Control Flow & Functions
Unit-2 Python Control Flow & Functions
A program’s control flow is the order in which the program’s code executes.
The control flow of a Python program is regulated by conditional statements, loops, and
function calls.
Python has three types of control structures:
Sequential - default mode
Selection - used for decisions and branching
Repetition - used for looping, i.e., repeating a piece of code multiple times.
Sequential:
Sequential statements are a set of statements whose execution process happens in a
sequence. The problem with sequential statements is that if the logic has broken in any one
of the lines, then the complete source code execution will break.
## This is a Sequential statement
a = 20
b = 10
c=a-b
print("Subtraction is : ", c)
Output:
Subtraction is: 10
These conditions can be used in several ways, most commonly in "if statements" and loops.
Example-1
n = 10
if n % 2 == 0:
print(n," is an even number")
Output:
10 is an even number
Example-2
# python program to illustrate If statement
i = 10
if (i > 15):
print("10 is less than 15")
print("I am Not in if")
Output:
I am Not in if
if-else: The if-else statement evaluates the condition and will execute the body of if if the
test condition is True, but if the condition is False, then the body of else is executed.
Syntax:
if (condition):
# executes this block if
# Condition is true
else:
# executes this block if
# Condition is false
PYTHON CONTROL FLOW & FUNCTIONS
Example-1
n=5
if n % 2 == 0:
print(n," is even")
else:
print(n," is odd")
Output:
5 is odd
Example-2
i = 20
if (i < 15):
print("i is smaller than 15")
print("i'm in if Block")
else:
print("i is greater than 15")
print("i'm in else Block")
print("i'm not in if and not in else Block")
PYTHON CONTROL FLOW & FUNCTIONS
Output:
i is greater than 15
i'm in else Block
i'm not in if and not in else Block
Example-1
x = 15
y = 12
if x == y:
print("Both are Equal")
elif x > y:
print("x is greater than y")
else:
print("x is smaller than y")
Output:
x is greater than y
Example-2
# Python program to illustrate if-elif-else ladder
i = 20
if (i == 10):
print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
print("i is not present")
Output:
i is 20
PYTHON CONTROL FLOW & FUNCTIONS
Example-1
a=5
b = 10
c = 15
if a > b:
if a > c:
print("a value is big")
else:
PYTHON CONTROL FLOW & FUNCTIONS
Example-2
# python program to illustrate nested If statement
i = 10
if (i == 10):
# First if statement
if (i < 15):
print("i is smaller than 15")
# Nested - if statement
# Will only be executed if statement above
# it is true
if (i < 12):
print("i is smaller than 12 too")
else:
print("i is greater than 15")
Output:
i is smaller than 15
i is smaller than 12 too
Short Hand If
If you have only one statement to execute, you can put it on the same line as the if
statement.
Example:
#One line if statement:
PYTHON CONTROL FLOW & FUNCTIONS
a = 200
b = 33
Output:
a is greater than b
Short Hand If ... Else
If you have only one statement to execute, one for if, and one for else, you can put it all on
the same line:
Example
#One line if else statement:
a=2
b = 330
print("A") if a > b else print("B")
Output:
B
Repetition
A repetition statement is used to repeat a group(block) of programming instructions.
In Python, we generally have two loops/repetitive statements:
for loop
while loop
for loop: A for loop is used to iterate over a sequence that is either a list, tuple, dictionary,
or a set. We can execute a set of statements once for each item in a list, tuple, or dictionary.
Syntax:
for iterator_var in sequence:
statements(s)
PYTHON CONTROL FLOW & FUNCTIONS
Example-1
# Python program to illustrate
# Iterating over range 0 to n-1
n=4
for i in range(0, n):
print(i)
Output:
0
1
2
3
Example-2
# Python program to illustrate
# Iterating over a list
print("List Iteration")
list = ["BCA", "BSc", "PESIAMS"]
for i in list:
print(i)
Tuple Iteration
BCA
BSc
PESIAMS
PYTHON CONTROL FLOW & FUNCTIONS
String Iteration
P
R
A
S
H
A
N
T
H
Dictionary Iteration
PES 123
IAMS 345
Set Iteration
1
2
3
4
5
6
Example-3
for i in range(1, 5):
for j in range(i):
print(i, end=' ')
print( )
Output:
while loop: In Python, while loops are used to execute a block of statements repeatedly
until a given condition is satisfied. Then, the expression is checked again and, if it is still
true, the body is executed again. This continues until the expression becomes false.
Syntax:
while expression:
PYTHON CONTROL FLOW & FUNCTIONS
statement(s)
Example-1
i=1
while i < 6:
print(i)
i += 1
Output:
Example-2
# Python program to illustrate while loop
count = 0
while (count < 3):
count = count + 1
print("PESIAMS")
Output:
PYTHON CONTROL FLOW & FUNCTIONS
Example-3
m=5
i=0
while i < m:
print(i, end = " ")
i=i+1
print("End")
Output:
Example
#Exit the loop when i is 3:
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
Output:
Continue statement
Continue is also a loop control statement just like the break statement. continue statement
is opposite to that of break statement, instead of terminating the loop, it forces to execute
the next iteration of the loop. As the name suggests the continue statement forces the loop
to continue or execute the next iteration. When the continue statement is executed in the
loop, the code inside the loop following the continue statement will be skipped and the next
iteration of the loop will begin.
Syntax:
Continue
PYTHON CONTROL FLOW & FUNCTIONS
Example
#Continue to the next iteration if i is 3:
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
Output:
Pass statement
As the name suggests pass statement simply does nothing. The pass statement in Python is
used when a statement is required syntactically but you do not want any command or code
to execute. It is like null operation, as nothing will happen is it is executed. Pass statement
PYTHON CONTROL FLOW & FUNCTIONS
can also be used for writing empty loops. Pass is also used for empty control statement,
function and classes.
Syntax:
pass
Example:
a = 33
b = 200
if b > a:
pass
# having an empty if statement like this, would raise an error without the pass statement
Output:
Parameter Values
Parameter Description
Example-1
#Create a sequence of numbers from 0 to 5, and print each item in the sequence:
x = range(6)
for n in x:
print(n)
Output:
Example-2
#Create a sequence of numbers from 3 to 5, and print each item in the sequence:
x = range(3, 6)
for n in x:
print(n)
Output:
Example-3
#Create a sequence of numbers from 3 to 19, but increment by 2 instead of 1:
x = range(3, 20, 2)
for n in x:
print(n)
PYTHON CONTROL FLOW & FUNCTIONS
Output:
Syntax:
exit( )
Example:
Output:
PYTHON CONTROL FLOW & FUNCTIONS
Python Functions
A function is a block of statements that return the specific task. (Function is a
block of code that performs a specific task) The idea is to put some commonly or
repeatedly done tasks together and make a function so that instead of writing the same
code again and again for different inputs, we can do the function calls to reuse code
contained in it over and over again.
Types of function
There are two types of function in Python programming:
Standard library functions - These are built-in functions in Python that are available to
use.
User-defined functions - We can create our own functions based on our requirements.
return num3
# Driver code
num1, num2 = 5, 15
ans = add(num1, num2)
print(f"The addition of {num1} and {num2} results {ans}.")
Output:
Output:
Sum: 9
Default Arguments
A default argument is a parameter that assumes a default value if a value is not provided in
the function call for that argument. In Python, we can provide default values to function
arguments. We use the = operator to provide default values.
The following example illustrates Default arguments.
def add_numbers( a = 7, b = 8):
sum = a + b
print('Sum:', sum)
# function call with two arguments
add_numbers(2, 3)
# function call with one argument
add_numbers(a = 2)
# function call with no arguments
add_numbers( )
Output:
Here, we have provided default values 7 and 8 for parameters a and b respectively. Here's
how this program works
1. add_number(2, 3)
Both values are passed during the function call. Hence, these values are used instead of the
default values.
2. add_number(2)
Only one value is passed during the function call. So, according to the positional
argument 2 is assigned to argument a, and the default value is used for parameter b.
3. add_number()
No value is passed during the function call. Hence, default value is used for both
parameters a and b.
Keyword Arguments
In keyword arguments, arguments are assigned based on the name of arguments.
The idea is to allow the caller to specify the argument name with values so that the caller
does not need to remember the order of parameters.
For example,
# Python program to demonstrate Keyword Arguments
def student(firstname, lastname):
print(firstname, lastname)
# Keyword arguments
student(firstname='PES', lastname='IAMS')
student(lastname='IAMS', firstname='PES')
Output:
Python Recursion
Recursion is the process of defining something in terms of itself.(Function call by itself)
PYTHON CONTROL FLOW & FUNCTIONS
In Python, we know that a function can call other functions. It is even possible for the
function to call itself. These types of construct are termed as recursive functions.
The following image shows the working of a recursive function called recurse.
Each function multiplies the number with the factorial of the number below it until it is
equal to one. This recursive call can be explained in the following steps.
Let's look at an image that shows a step-by-step process of what is going on:
PYTHON CONTROL FLOW & FUNCTIONS
Our recursion ends when the number reduces to 1. This is called the base condition.
Every recursive function must have a base condition that stops the recursion or else the
function calls itself infinitely.
The Python interpreter limits the depths of recursion to help avoid infinite recursions,
resulting in stack overflows.
By default, the maximum depth of recursion is 1000. If the limit is crossed, it results
in RecursionError. Let's look at one such condition.
def recursor( ):
recursor( )
recursor( )
Output:
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.