Unit 2 Python
Unit 2 Python
Introduction
In previous chapter we have already covered the core essentials of python like identifiers,
variables, expressions and operators. Now we will understand the various constructs around
code development of a given problem in Python.
In this sequence, we will learn how to control the flow of the execution of a code developed for
a given problem.
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 and iteration statements (loops).
We perform many actions based on various decisions taken in our daily life such as, switch on
the room lights; drink a hot coffee or not, or wear a rain coat or not?
• For switch on the light, the condition may be the darkness in room or not.
• For drinking a hot coffee, the conditions may be cold weather or good coffee.
• For carrying the raincoat, the conditions may be rainy weather.
If the conditions are true, we perform the desired action and if the condition is false, we perform
the alternative action or no action.
In figure 2.1(a), we observe that if the condition is true such as “if there is darkness in room”
action will be performed as “Lights will be switched on” and “if weather is cold “action will be
performed as “Drink Coffee”.
But if condition is false such as “if there is no darkness in room” the alternative action will be
performed such as “no need to switch on the lights means Do Nothing” and “if “weather is not
cold” the alternative action will be performed as “Have a soft drink”.
Figure 2.1(a) Real life scenario: Conditions with actions with false condition
In above figure we can control that if the condition is true, what will be the action and if condition
fails, what will be the action.
Like taking decisions to perform various actions, we repeat the same action many times in our
day to day life.
Suppose you went to the market to purchase a T-shirt. Now, you will visit each and every single
shop until you get your desired T-shirt and when you find it you return to your home as shown in
figure 2.1(b).
That’s how loop work, it will also perform the task until the condition will not be met.
In this chapter, we will focus on decision control and iteration control in python programming.
We will understand the types of decision control system and iteration control in Python, the
various terminology, syntax and usage.
Decision control statement used to control the flow of execution of program depending upon
condition, if the condition is true then the code block will execute and if the condition is false
then code block will not execute and execution change to different code block.
Example: Suppose the teacher decided to grade students as excellent, good, average and below
average on the basis of their marks. The conditions of marks are as follows and shown in figure
2.2(a).
The above grading system depends on the TRUE or FALSE values obtained on evaluation of the
conditional expression as depicted in Figure 2.2(b). On the basis of the input marks,
corresponding block of code will be executed or not, will be based on the result return by checked
condition.
For example, if input marks are 85, the condition Marks <=95 and Marks > 80 will return TRUE
and the code block corresponding to the condition i.e. Good will be print.
This is how, the execution flow of code can be controlled by selection/decision control
statements in Python.
if statement evaluates whether a condition is true or false. The block of statement/code will be
executed, if and only if, the specified condition is true.
Note: As we use curly braces in ‘C’ Language to define the scope of conditions and loops; in the
same manner we use colon (:) and indentation in Python as shown in the figure 2.2.1(b).
The Figure 2.2.1(b) represents the syntax of if statement. As the conditional expression becomes
TRUE, the statements inside if i.e. statement 1, statement 2… statement nth, will get executed in
a sequential manner. After the execution of the body of if, the code after if body will get
executed. If the conditional expression is evaluated as FALSE, then the block of statements inside
if will not be executed. Only the statements after the end of if code block, i.e. the statement (nth
+ 1) will get executed.
n is an even number
In the example 1, the condition n%2 == 0 is True for value of n = 10, so the statement print (“n
is an even number”) will be executed. The output will be “n is an even number”.
Output:
11
In above example 2, the condition x>0 is True for value of x = 10 so the statements in the block
of code will be executed. The statement x = x+1 will increment the value of x by 1 i.e. x = 10 + 1;
x = 11 and statement print (x) will print x value as 11.
Note: It is not mandatory to put small brackets( )to specify conditional expression with if
keyword as shown in below example.
if True:
print("Hello, world!")
Hello, world!
Practice Exercise:
1. Write a program to check if input year is leap year.
2. Write a program to check that input number is odd.
In “if” conditional statement, we have one condition and if the condition is true, there is a block
of code to be executed. There is no code execution in case of condition failure. If we have two
block of codes and we have to decide which block of code to be executed on the basis on
conditional expression as shown in figure 2.2.2(a).
Flowchart:
An if…else statement in python checks whether a condition is true or false. If a condition is true,
the if statement executes. Otherwise, the else statement executes.
The Figure 2.2.2(b) represents the syntax of if-else statements. As the conditional expression
becomes TRUE, the statements inside the if block get executed. After the execution of the body
of if, the statement just after if else get executed.
If the conditional expression of if statement is evaluated as FALSE, then the set of statements
inside the else block got executed. After the execution of the body of else, the statement just
after else get executed.
Example 1: Write a program to print “Excellent” if marks is greater than 95 otherwise print
“Good”
Output
In the above example 1, for input value 96, the condition marks > 95 is True, so the statement
print (“Excellent”) will be executed. The output will be “Excellent”.
Example 2: Write a program to print “Excellent” if marks is greater than 95 otherwise print
“Good”
Output
In the above example 2, for input value 68, the condition marks > 95 is False, so the control goes
to the else statement print (“Good”) will be executed. The output will be “Good”.
Practice Exercise:
The if-elif statement is an extension of the if-else statement. When we have multiple conditional
statements, then we use if-elif statement. You can use as many elif statements as you want.
Syntax:
The Figure 2.2.3 (a) represents the syntax of if-elif-else ladder. As the conditional expression of if
executes TRUE, the statements inside the if block will get executed, if the condition is False then
next elif conditional expression executes; if it executes to TRUE, then the statements inside the
elif block will get executed and so on. If all the conditions fail, then else body will be executed if
it is present in the code.
Flowchart:
Figure 2.2.3(b) Flow Chart of If-elif statement
Note: The conditional expression of if-elif-else are executed from top to bottom in a sequential
manner. An elif statements are known as elif Ladder.
In the above example 1, for input value 88, the condition marks > 95 is False and control goes to
next elif statement (marks>80 and marks<=95), which is True and statement print (“Good”) will
be executed. The output will be “Good”.
Practice Exercise:
1. Write a program to generate electricity bill on basis of following criteria. First 100 units
as 3 rupees per unit, next 100 units as 4 rupees per unit and then rest would be
calculated as 5 rupees per unit. Total units consumed would be entered by user and
program should print the total billing amount.
2. Write a program to calculate salary on the basis of following criteria if basic<20000,
DA is 30%. If 20000<=basic<30000 Da is 40%. User would input basic and program
should print total salary.
3. Write a program to take an integer number from 1 to 7 from user and print
corresponding weekday, consider 1 as Monday, also print if there is incorrect choice.
When an if-else statement is present inside the body of another “if” or “else” then this is called
nested if else.
Syntax:
Flowchart:
Example: Write a program to take age as input from user and print “You are less than 18” if age
is less than 18, otherwise print “You are above 18”. You should also check that age could not be
less than 0. If so then print a message “Age could not be less than 0”.
In above example, for input value 20, the condition age > 0 is TRUE and it enters in if block. If it
would have false, it would had entered into else block. As shown in example, age is 20, which is
True, it would enter into if block where it again checks for age<18, which is false in our case so
its else part would execute and output will be “You are above 18”.
Example: Write a program to take age as input from user and print “You are less than 18” if age
is less than 18, otherwise print “You are above 18”. You should also check that age could not be
less than 0. If so then print a message “Age could not be less than 0”.
In above example, for input value -1, the condition age > 0 is FALSE and else block will be
executed and output will be “Age could not be less than 0”.
Practice Exercise:
1. Write a program to find the maximum of three numbers.
2. Write a program to enter integer from 1 to 12 and print corresponding number of days in
the month.
In daily life we come across many situations when we repeat same set of operations again and
again.
Let’s continue our conditional example of the section 2.2.
Example - Suppose the teacher decide to grade students on the basis of marks and he wants to
do this for whole class. So, teacher would repeat grading procedure for each student in the
class, this is called iterative/ looping.
Figure 2.3 Flow of looping
In the figure 2.3 a concept of iterative/looping explained with the help of flow diagram, where
the block of code for grading system will execute till no students left for grading.
While Loop is used to repeat a block of code as long as a given condition is True. We take an
initialized variable and we keep on incrementing or decrementing it, as per our requirements
till we met false condition, failing to increment/decrement would lead to infinite loop.
Syntax:
Figure 2.3.1(a): Syntax of while loop
Flowchart:
Example 1: Write a program to print 4 natural numbers i.e. 1,2,3,4 using while loop.
In above example 1, the variable i is initialized with value ‘1’. Therefore, the conditional
expression, i < 5 becomes TRUE then print(i) is executed and the value of i is increased by 1.
Every time condition is checked and values is incremented by 1 along with the print command.
In last iteration the conditional expression, i < 5 becomes FALSE and while loop gets terminated.
Nested while loop is called when we use while loop inside a while loop. In python we can use
any number of while loop inside a while loop.
Generally, we call main while loop as outer while loop and nested while loop as inner while loop.
If outer loop running m times and inner loop running n times, then total iterations would be m*n.
Syntax:
Note: Outer while loop expression is evaluated first. When its return true, the control jumps to the
inner while loop till its completion. However, flow of control comes out of inner while loop if the
expression returns false.
Before for loop we should know range () function because for loop works with sequences and
range () provides us desired sequence.
range ()
range () function is built-in function in python which gives the sequence of numbers. If you
want the integer values from 1 to 10 i.e. 1,2,3,4,5,6,7,8,9,10 then range () is a useful built-in
function to work on.
where,
Stop value: Stop value is required field, which indicates where to stop the values. The stop
value never included in range.
Step value: Step value is optional, by default the step value is +1. Step value notifies the
interval of values.
Example: if we take range (1,5,1), it will generate a sequence starting from value 1 up to value
4(5 is not included) and step by 1.
Note: range () function returns the range object. So, you need to typecast the range object into
collections.
If the range () function is called with one parameter only, this is considered as the stop value. It
means the start value is considered as 0, and step value is considered as 1.
Syntax:
In the above-mentioned figure, the single value 5 denotes the stop value. In the output, you can
see the start value is 0 and last mentioned value is 4 i.e. stop value minus -1. We know that range
function returns the range object, so type conversion is used. That’s why the output is in list
format i.e. [0, 1, 2, 3, 4]
2.4.2. range () with two argument
If the range () function has two parameters in it, this means the start value and stop value is
mentioned, whereas the step values is considered as 1 by default.
Syntax:
In the above-mentioned figure, two values are given where the first value is starting value and
the second value is stop value. In the output, you can see the start value is 1 and last-mentioned
value is 4 i.e., stop value minus 1. We know that range function returns the range object, so type
conversion is used. That’s why the output is in list format i.e. [1, 2, 3, 4]
If the range () function has three parameters in it, this means the start value, stop value and
the step value, all three values are given inside range ().
Syntax:
Fig 2.4.3 Range with three arguments
Here first start value is 1, stop value 5 and step value is 2. That’s why the output is [1, 3] .
for loop is used when we want to run a part of our program multiple times. It is also used to
traverse sequences in python like lists, tuple etc. (Details in chapter 3).
Syntax:
Flow chart:
As shown in flowchart the statements which we want to run multiple times would keep on
running till, we have elements in the sequence. As no element left, it will come out from loop.
Figure 2.5(b) Flowchart of for loop
Example 1: First example we would use for loop with range function which is discussed in
previous section.
In this example-1,
• i is the iterating variable
• sequence is range (10) - it will generate sequence of value from 0 to 9
• statement is print(i)
Example 2: In this example table of number 5 is printed using for loop. As table starts with
multiplier 1 and ends to 10, we have taken range of (1,11) which would generate sequence of
elements from 1,2,3…10.
In this example-2,
• i is the iterating variable
• sequence is range (1,11)
• statement is print(i,”* 5=”,i*5)
Nested for loop is called when we use for loop inside a for loop. In python we can use any
number of for loop inside a for loop.
Generally, we call main for loop as outer for loop and nested for loop as inner for loop. If outer
loop running m times and inner loop running n times, then total iterations would be m*n.
Syntax
Figure 2.5.1(a) Syntax of nested for loop
Flow chart
Example 1: In this example we have used two for loops. Outer loop is running for two values-0
and 1 and inner loop is running for three values-0,1 and 2 and total print statements we are
getting 2*3=6.
Practice Exercise:
1. Write a program using for loop to print first and last digit of any number.
2. Write a program using for loop to find the factor of any number.
Jump statements are used to jump, skip or terminate the iteration or loop from the running
program at the particular condition. These are also known as early exit from loop. They are used
mainly to interrupt loops. Jump statements are break and continue.
2.6.1 Break
Break statement terminates the execution of loop immediately, and the program execution will
jump to the next statements.
Syntax:
Flowchart:
________________________________________________________________________
In the above example, when value of I would be 3 break statement will be executed and loop will
be terminated and control moves outside the while loop to print “All done”. If there would have
no break, then loop would had run for i=1 to 4.
2.6.2 Continue
Continue is used to skip the ongoing iteration and continues the remaining iterations of loop. Use
of continue statement is to jump to the next iteration by skipping the existing one.
Syntax:
Figure 2.6.2(a) Syntax of continue statement
In the above figure, if while loop condition 1 is true, the control goes inside the while loop, if the
condition 2 is true, the control goes to the continue statement. Continue statement will
Note: In break statement, the whole loop will end; and in continue statement, only the specific
iteration will end.
terminate the on-going iteration and skip the next statements i.e. statement 1 and statement 2.
Here the statement1 and statement2 will be skipped by the continue keyword and the control
goes back to the while loop for upcoming iterations.
Flowchart:
In the above example, the continue statement will interrupt the on-going iteration for i=3 and
skip all the statements of current iteration which are mentioned after the continue statement
like print(i). The control goes back to the while loop for next iteration and loop moves on. In the
output, you can see only the value 3 is missing due to the continue statement.
If the condition in the while loop evaluates to False, the else portion of the code runs. And if
break statement is used in while loop then else section is not taken into consideration.
Syntax:
Note: The else clause will be executed when the condition becomes False and the loop runs normally.
The else clause, on the other hand, will not execute if the loop is terminated early by a break or return
statement.
In above example 2, while loop will get terminated when value of condition variable = 3, So else
block will not be executed.
Python allows else with for loop. When all the iteration of for loop are finished normally, then
control goes to else part. If loop has a break statement, then else part would not execute.
Flow chart:
In this example we have used break statement with the condition for i=5, so in the output we
are getting values from 0 to 4 and then no else part executed.
Practice Exercise: