You are on page 1of 9

Python Programming Unit-2 Notes

CHAPTER 2- Control flow & Function in Python

Conditional execution
In order to write useful programs, we almost always need the ability to check conditions and
change the behaviour of the program accordingly. Conditional statements give us this ability.
if statement
The if statement is used to test a particular condition and if the condition is true, it executes a
block of code known as if-block .The condition of if statement can be any valid logical expression
which can be either evaluated to true or false.

The syntax of the if-statement is given below.

if (condition):
#statement1
#extra statements....
#statement2

# Here if the condition is true, if block


# will consider only statement1 and extra statements to be inside its block.
# statement 2 is outside of if block.

Example:-

# Python program to illustrate If statement

i = 10
if (i> 15):
print("10 is less than 15")
print("I am not in if")

I am not in if

As the condition present in the if statement is false. So, the block below the if statement is not
executed.

if-else
The if-else statement provides an else block combined with the if statement which is executed
in the false case of the condition.

If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.
Python Programming Unit-2 Notes

if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false

# Python program to illustrate If else statement

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")

I is greater than 15
I'm in else Block
I'm not in if and not in else Block

The block of code following the else statement is executed as the condition present in the if statement
is false after calling the statement which is not in block (without spaces).

Nested-if

A nested if is an if statement that is the target of another if statement. Nested if statements


mean an if statement inside another if statement. Python allows us to nest if statements within if
statements. i.e., we can place an if statement inside another if statement.

if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Python Programming Unit-2 Notes

# 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")

i is smaller than 15
i is smaller than 12 too

If-elif-else ladder
The if statements are executed from the top down. As soon as one of the conditions
controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is
bypassed. If none of the conditions is true, then the final else statement will be executed.
if (condition):
statement
elif (condition):
statement
.
.
else:
statement

# Python program to illustrate if-elif-else ladder

i = 15
if (i == 10):
print("i is 10")
elif (i == 15):
print("i is 15")
else:
print("i is not present")

Looping statements:
i is 15
Python Programming Unit-2 Notes

In general, statements are executed sequentially: The first statement in a function is executed
first, followed by the second, and so on. There may be a situation when you need to execute a block
of code several number of times.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times.

while loop
In python, while loop is used to execute a block of statements repeatedly until a given a condition is
satisfied. And when the condition becomes false, the line immediately after the loop in program is
executed.
while (expression) :
statement(s)

All the statements indented by the same number of character spaces after a programming construct
are considered to be part of a single block of code. Python uses indentation as its method of grouping
statements.

# Python program to illustrate while loop


count = 0
while count <3 :
count = count + 1
print("Hello World")

Hello World
Hello World
Hello World

As discussed above, while loop executes the block until a condition is satisfied. When the condition
becomes false, the statement immediately after the loop is executed.
The else clause is only executed when your while condition becomes false. If you break out of the
loop, or if an exception is raised, it won’t be executed.

#Python program to illustrate combining else with while


count = 0
while (count < 1):
count = count + 1
print("Hello World")
else:
print("In Else Block")

Hello World
for
In loop
Else Block
Python Programming Unit-2 Notes

For loops are used for sequential traversal. For example: traversing a list or string or array etc.
In Python, there is no C style for loop, i.e., for (i=0; i<n; i++). It can be used to iterate over a range
and iterators.

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.

range(start, stop, step)

Parameter Description
# Python program to illustrate Iterating over range 0 to n-1
  Start Optional. An integer number specifying at which position to start. Default is
n=4 0
for i in range(0, n):
    print(i)
Stop Required. An integer number specifying at which position to stop (not
included).
0
1 Step Optional. An integer number specifying the incrementation. Default is 1
2
3

# Using range to print numberdivisible by 3


for i in range(0, 30, 3):
print(i, end=" ")
print()

0 3 6 9 12 15 18 21 24 27
If a user wants to decrement, then the user needs steps to be a negative number. For example:

# Python program to decrement with range()


# incremented by -2

for i in range(25, 2, -2):


print(i, end=" ")
print()

25 23 21 19 17 15 13 11 9 7 5 3

Using else statement with for loops


Python Programming Unit-2 Notes

We can also combine else statement with for loop like in while loop. But as there is no
condition in for loop based on which the execution will terminate so the else block will be executed
immediately after for block finishes execution.

# Python program to illustrate combining else with for

list = ["ABC", "BCD", "CDE"]


for index in range(len(list)):
print(list[index])
else:
print("Inside Else Block")

ABC
BCD
CDE
Inside Else Block

Nested loops
Python programming language allows to use one loop inside another loop.

# Python program to illustrate nested for loops

for i in range(1, 5):


for j in range(i):
print(i, end=' ')
print()

1
22
333
4444
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.

ContinueStatement: It returns the control to the beginning of the loop

# Prints all letters except 'e' and 'o'



for letter in 'Python':
if letter == 'e' or letter == 'o':
continue
print('Current Letter :', letter)

Current Letter : P
Python Programming Unit-2 Notes

Break Statement: It brings control out of the loop for letter

# Break the loop as soon it sees 't'

for letter in 'python':


if letter == 't':
break
print('Current Letter :', letter)

Current Letter : t

Pass Statement: We use pass statement to write empty loops. Pass is also used for empty control
statement, function and classes.

# An empty loop

for letter in 'python':


pass
print('Last Letter :', letter)

Last Letter : n
Functions
Python Functions is a block of related statements designed to perform a computational,
logical, or evaluative 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. 
Functions can be either built-in or user-defined. It helps the program to be concise, non-repetitive,
and organized.
deffunction_name(parameters):
statement(s)
return expression
Python Programming Unit-2 Notes

Creating a function
We can create a Python function using the def keyword.

# A simple Python function

def fun():
print("Python Programming")

Calling a function
After creating a function 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("Python Programming")

# Driver code to call a function


fun()

Python Programming

Types of Arguments
Python supports various types of arguments that can be passed at the time of the function call.
Let’s discuss each type in detail.

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. The following example illustrates Default arguments.

# Python program to demonstrate default arguments

def myFun(x, y=50):


print("x: ", x)
print("y: ", y)

# Driver code (We call myFun() with only argument)


myFun(10)
Python Programming Unit-2 Notes

Keyword arguments
The idea is to allow the caller to specify the argument name with values so that caller does not need
to remember the order of parameters.

# Python program to demonstrate Keyword Arguments

def student(firstArg, lastArg):


    print(firstArg, lastArg)
 
# Keyword arguments
student(firstArg='Python', lastArg ='Practice')
student(lastArg ='Practice', firstArg='Python')

Python Practice
Python Practice

You might also like