0% found this document useful (0 votes)
6 views30 pages

Unit-2 Python Control Flow & Functions

The document provides an overview of control flow and functions in Python, detailing the types of control structures such as sequential, selection, and repetition. It explains various control statements like if, if-else, loops, and the use of functions, including their declaration, calling, and parameters. Additionally, it covers loop control statements and the benefits of using functions for code reusability and readability.

Uploaded by

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

Unit-2 Python Control Flow & Functions

The document provides an overview of control flow and functions in Python, detailing the types of control structures such as sequential, selection, and repetition. It explains various control statements like if, if-else, loops, and the use of functions, including their declaration, calling, and parameters. Additionally, it covers loop control statements and the benefits of using functions for code reusability and readability.

Uploaded by

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

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

Selection/Decision control statements


In Python, the selection statements are also known as Decision control
statements or branching statements.
The selection statement allows a program to test several conditions and execute
instructions based on which condition is true.
Python supports the usual logical conditions from mathematics:
 Equals: a == b
 Not Equals: a != b
 Less than: a < b
 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b
PYTHON CONTROL FLOW & FUNCTIONS

These conditions can be used in several ways, most commonly in "if statements" and loops.

Some Decision Control Statements are:


 Simple if
 if-else
 nested if
 if-elif-else
Simple if: If statements are control flow statements that help us to run a particular code,
but only when a certain condition is met or satisfied. A simple if only has one condition to
check.
Syntax:
if condition:
statement1
statement2

# Here if the condition is true, if block


# will consider only statement1 to be inside
# its block.
PYTHON CONTROL FLOW & FUNCTIONS

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

If-elif-else: The if-elif-else statement is used to conditionally execute a statement or a block


of statements.
Syntax:
if (condition):
statement
elif (condition):
statement
.
.
else:
statement
PYTHON CONTROL FLOW & FUNCTIONS

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

nested if: Nested if statements are an if statement inside another if statement.


Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here

Example-1
a=5
b = 10
c = 15
if a > b:
if a > c:
print("a value is big")
else:
PYTHON CONTROL FLOW & FUNCTIONS

print("c value is big")


elif b > c:
print("b value is big")
else:
print("c is big")
Output:
c is big

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

if a > b: print("a is greater than b")

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)

# Iterating over a tuple (immutable)


print("\nTuple Iteration")
PYTHON CONTROL FLOW & FUNCTIONS

tuple = ("BCA", "BSc", "PESIAMS")


for i in tuple:
print(i)

# Iterating over a String


print("\nString Iteration")
s = "PRASHANTH"
for i in s:
print(i)

# Iterating over dictionary


print("\nDictionary Iteration")
d = dict( )
d['PES'] = 123
d['IAMS'] = 345
for i in d:
print("%s %d" % (i, d[i]))

# Iterating over a set


print("\nSet Iteration")
set1 = {1, 2, 3, 4, 5, 6}
for i in set1:
print(i)
Output:
List Iteration
BCA
BSc
PESIAMS

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:

Loop control statements:


Using loops in Python automates and repeats the tasks in an efficient manner. But
sometimes, there may arise a condition where you want to exit the loop completely, skip an
iteration or ignore that condition. These can be done by loop control statements. Loop
control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed. Python supports
the following control statements.
 Break statement
 Continue statement
 Pass statement
Break statement
The break statement is used to terminate the loop or statement in which it is present. After
that, the control will pass to the statements that are present after the break statement, if
available. If the break statement is present in the nested loop, then it terminates only those
loops which contain break statement.
Syntax:
break
PYTHON CONTROL FLOW & FUNCTIONS

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:

Python range( ) Function


The range( ) function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and stops before a specified number.
Syntax:
range(start, stop, step)

Parameter Values

Parameter Description

start Optional. An integer number specifying at which position to start. Default


is 0

stop Required. An integer number specifying at which position to stop (not


included).

step Optional. An integer number specifying the incrementation. Default is 1


PYTHON CONTROL FLOW & FUNCTIONS

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:

Python exit ( ) Function


Python provides the option and permission for a programmer to terminate a Python
program at any time. We can utilize Python's built-in exit( ) function to exit and exit the
program's execution loop.

Syntax:
exit( )

Example:

#demonstration of exit( ) function


for x in range(3, 10):
print(x + 20)
exit( )

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.

Benefits of Using Functions


1. Code Reusable - We can use the same function multiple times in our program which
makes our code reusable.
2. Code Readability - Functions help us break our code into chunks to make our program
readable and easy to understand.

Python Function Declaration


The syntax to declare a function is:
PYTHON CONTROL FLOW & FUNCTIONS

Creating a Function in Python


We can create a user-defined function in Python, using the def keyword. We can add any
type of functionalities and properties to it as we require.
# A simple Python function
def fun( ):
print("Welcome to PESIAMS")

Calling a Python Function


After creating a function in Python, we can call it by using the name of the function
followed by parenthesis containing parameters of that particular function.
# A simple Python function
def fun( ):
print("Welcome to PESIAMS")
# Driver code to call a function
fun( )
Output:

Python Function with Parameters


Defining and calling a function with parameters
def function_name(parameter: data_type) -> return_type:
"""Docstring"""
# body of the function
return expression
Example-1
def add(num1: int, num2: int) -> int:
"""Add two numbers"""
num3 = num1 + num2
PYTHON CONTROL FLOW & FUNCTIONS

return num3
# Driver code
num1, num2 = 5, 15
ans = add(num1, num2)
print(f"The addition of {num1} and {num2} results {ans}.")
Output:

Python Function Arguments


Arguments are the values passed inside the parenthesis of the function. A function can have
any number of arguments separated by a comma.
In this example, we will create a simple function in Python to check whether the number
passed as an argument to the function is even or odd.
# A simple Python function to check
# whether x is even or odd
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
# Driver code to call the function
evenOdd(2)
evenOdd(3)
Output:
PYTHON CONTROL FLOW & FUNCTIONS

Example 1: Python Function Arguments


# function with two arguments
def add_numbers(num1, num2):
sum = num1 + num2
print("Sum: ",sum)
# function call with two values
add_numbers(5, 4)

Output:
Sum: 9

The return Statement in Python


A Python function may or may not return a value. If we want our function to return some
value to a function call, we use the return statement.
For example,
def add_numbers():
...
return sum
Here, we are returning the variable sum to the function call.
Note: The return statement also denotes that the function has ended. Any code after return
is not executed.
PYTHON CONTROL FLOW & FUNCTIONS

Example: Function return Type


# function definition
def find_square(num):
result = num * num
return result
# function call
square = find_square(3)
print('Square:',square)
Output:
Square: 9
In the above example, we have created a function named find_square(). The function
accepts a number and returns the square of the number.

Example: Add Two Numbers


# function that adds two numbers
def add_numbers(num1, num2):
sum = num1 + num2
return sum
# calling function with two values
result = add_numbers(5, 4)
print('Sum: ', result)
Output:
Sum: 9
PYTHON CONTROL FLOW & FUNCTIONS

Python Library Functions


In Python, standard library functions are the built-in functions that can be used directly in
our program. For example,
 print() - prints the string inside the quotation marks
 sqrt() - returns the square root of a number
 pow() - returns the power of a number
These library functions are defined inside the module. And, to use them we must include
the module inside our program.
For example, sqrt() is defined inside the math module.
Example: Python Library Function
import math
# sqrt computes the square root
square_root = math.sqrt(4)
print("Square Root of 4 is",square_root)
# pow() comptes the power
power = pow(2, 3)
print("2 to the power 3 is",power)
Output:
Square Root of 4 is 2.0
2 to the power 3 is 8
In the above example, we have used
 math.sqrt(4) - to compute the square root of 4
 pow(2, 3) - computes the power of a number i.e. 23
Here, notice the statement,
import math
Since sqrt( ) is defined inside the math module, we need to include it in our program.
PYTHON CONTROL FLOW & FUNCTIONS

Types of Python Function Arguments


Python supports various types of arguments that can be passed at the time of the function
call. In Python, we have the following 4 types of function arguments.
 Default argument
 Keyword arguments (named arguments)
 Positional arguments
 Arbitrary arguments (variable-length arguments *args and **kwargs)

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:

In the above example, notice the function definition


def add_numbers(a = 7, b = 8):
...
PYTHON CONTROL FLOW & FUNCTIONS

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.

Following is an example of a recursive function to find the factorial of an integer.


Factorial of a number is the product of all the integers from 1 to that number. For example,
the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.
Example of a recursive function
def factorial(n):
"""This is a recursive function
to find the factorial of an integer"""
if n == 1:
return 1
else:
return (n * factorial(n-1))
n=int(input("Enter the value of n\n"))
print("The factorial of", n, "is", factorial(n))
Output:

In the above example, factorial( ) is a recursive function as it calls itself.


When we call this function with a positive integer, it will recursively call itself by
decreasing the number.
PYTHON CONTROL FLOW & FUNCTIONS

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.

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

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.

3. Recursive functions are hard to debug.

You might also like