0% found this document useful (0 votes)
2 views

Unit-2 Python Control Flow-Functions

This document covers Python control flow, including sequential, selection, and repetition structures. It explains various control statements such as if, if-else, and loops (for and while), along with examples. Additionally, it discusses functions, their types, and how to create and call them, including the use of parameters and recursion.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Unit-2 Python Control Flow-Functions

This document covers Python control flow, including sequential, selection, and repetition structures. It explains various control statements such as if, if-else, and loops (for and while), along with examples. Additionally, it discusses functions, their types, and how to create and call them, including the use of parameters and recursion.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Unit-2 Python Control Flow IV Semester BCA

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
These conditions can be used in several ways, most commonly in "if statements" and loops.
Unit-2 Python Control Flow IV Semester BCA

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.

Example-1
n = 10
Unit-2 Python Control Flow IV Semester BCA

if n % 2 == 0:
print(n," is an even number")
Output:
10 is an even number

if-else

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

Example-1
n=5
if n % 2 == 0:
print(n," is even") else:
print(n," is odd") Output:
5 is odd
Unit-2 Python Control Flow IV Semester BCA

elif
elif: 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

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
Unit-2 Python Control Flow IV Semester BCA

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:
print("c value is big") elif
b > c:
print("b value is big") else:
print("c is big") Output:
c is big
Repetition
A repetition statement is used to repeat a group(block) of programming instructions.
Unit-2 Python Control Flow IV Semester BCA

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)

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
Unit-2 Python Control Flow IV Semester BCA

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:
statement(s)

Example-1
i = 1 while
i < 6:
print(i)
i += 1
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
Unit-2 Python Control Flow IV Semester BCA

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

Example
#Exit the loop when i is 3:
i = 1 while
i < 6:
print(i) if
i == 3:
break
i += 1
Output:
Unit-2 Python Control Flow IV Semester BCA

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.
Syntax:
Continue

Example
#Continue to the next iteration if i is 3:
i = 0 while
i < 6:
i += 1
if i == 3:
continue
print(i)
Output:
Unit-2 Python Control Flow IV Semester BCA

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
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)
Unit-2 Python Control Flow IV Semester BCA

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

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:

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:
Unit-2 Python Control Flow IV Semester BCA

exit( )

Example:

#demonstration of exit( ) function for


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

Output:
Unit-2 Python Functions IV Semester BCA

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:

1
Unit-2 Python Functions IV Semester BCA

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 return
2
Unit-2 Python Functions IV Semester BCA

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:

Example 1: Python Function Arguments


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

3
Unit-2 Python Functions IV Semester BCA

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.

Example: Function return Type


# function definition def
find_square(num):
result = num * num
return result # function
call square =
find_square(3)

4
Unit-2 Python Functions IV Semester BCA

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.

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
5
Unit-2 Python Functions IV Semester BCA

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.
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:

6
Unit-2 Python Functions IV Semester BCA

In the above example, notice the function definition def


add_numbers(a = 7, b = 8):
...
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:

7
Unit-2 Python Functions IV Semester BCA

Python Recursion
Recursion is the process of defining something in terms of itself.(Function call by itself)
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.
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.

8
Unit-2 Python Functions IV Semester BCA

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:

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.
1. 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