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

Unit 2 Python

The document discusses control flow in Python programs. Control flow refers to the order in which the program executes statements and makes decisions about execution. There are two main types of control flow statements in Python: conditional statements (if/else) and iteration statements (loops). Conditional statements like if/else allow a program to execute different code blocks based on whether a condition is true or false. Real-world examples of conditional logic are presented. If/else statements provide two blocks, while if/elif/else allows checking multiple conditions in order. Iteration statements like loops repeat a block of code until a certain condition is met. A real-world example of repetition is presented with shopping for a t-shirt. Loops

Uploaded by

ANSH SINGH
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
85 views

Unit 2 Python

The document discusses control flow in Python programs. Control flow refers to the order in which the program executes statements and makes decisions about execution. There are two main types of control flow statements in Python: conditional statements (if/else) and iteration statements (loops). Conditional statements like if/else allow a program to execute different code blocks based on whether a condition is true or false. Real-world examples of conditional logic are presented. If/else statements provide two blocks, while if/elif/else allows checking multiple conditions in order. Iteration statements like loops repeat a block of code until a certain condition is met. A real-world example of repetition is presented with shopping for a t-shirt. Loops

Uploaded by

ANSH SINGH
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

2.1.

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?

These decisions based on many conditions such as:

• 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).

Figure 2.1(b) Real life scenario: Task Repetition

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.

2.2 Selection/Decision Control Statements

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

• Excellent : Marks obtained above 95%.


• Good : Marks obtained greater than 80% and less than equal to 95%.
• Average : Marks obtained greater than 60% and less than equal to 80%.
• Below average : Marks obtained less than 60%

Figure 2.2(a) Graphical representation of grading system.


The above-mentioned example has been represented in Flowchart in the below diagram to show
the conditional expressions (the conditions are represented in diamond box in the flowchart).

Figure 2.2(b) Flow chart of grading system

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.

In Python programming, there are four types of decision/selection control statements:


• Simple if
• if-else
• if-elif-else
• nested if-else

2.2.1 Simple if statement

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.

Figure 2.2.1(a) Flow Chart of If statement


Syntax of Simple if:

Figure 2.2.1(b) Syntax of If statement

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.

Example 1: Print whether a number is even or not


Output:

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

Example 2: Write a program to increment a number if it is positive.

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.

2.2.2 if-else statement

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:

Figure 2.2.2(a) Flowchart of If else statement


Syntax:

Figure 2.2.2(b) Syntax of If..else statement

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:

1. Write a program to know profit or loss in a particular sell and purchase.


2. Write a program to check if user has got honours in the examination or not.
2.2.3 if-elif statement

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:

Figure 2.2.3(a) Syntax of if-elif statement

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.

Example 1: Write a program to print grade of students according to following condition.


o Excellent : Marks obtained above 95%.
o Good : Marks obtained greater than 80% and less than equal to 95%.
o Average : Marks obtained greater than 60% and less than equal to 80%.
o Below average : Marks obtained less than 60%
Output

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.

2.2.4 Nested if-else statement

When an if-else statement is present inside the body of another “if” or “else” then this is called
nested if else.
Syntax:

Figure 2.2.4(a) Syntax of nested If statement

Flowchart:

Figure 2.2.4(b) Syntax of nested If-else statement


The Figure 2.2.4(a) represents the syntax of nested if-else statements. As the conditional
expression 1 becomes TRUE, the statements inside the first if block will get executed as depicted
in figure 2.2.4(b). Now, another condition is evaluated by means of nested if conditional
expression 2. As it is evaluated TRUE, the set of statement inside nested if will be executed and
so on.

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.

2.3 Iterative/Looping Statements

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.

In python we have two type of loops –


• While loop
• For loop
Both of these loops have been discussed in subsequent sections.

2.3.1 While loop

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:

Figure 2.3.1(b): Flowchart of while loop.

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.

2.3.2 Nested While loop

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:

Figure 2.3.2(a): Syntax of Nested while loop


Flowchart:

Figure 2.3.2(b): Flowchart of Nested while loop.

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.

Example 1: Program to demonstrate the nested while loop


In above example 1, outer loop is running 3 times and inner loop is also running for 3 times, so
loop would run 3X3=9 times. As you can see in output for every iteration of outer loop, inner loop
executed 3 times.
Practice Exercise:
1. Write a program to print natural for first n numbers, where n would be entered
by user.
2. Write a program to print all even numbers from 75 to 150.

2.4 range () function

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.

Syntax of range ():

where,

Start value: start value is optional, by default it is 0.

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.

So the output of range (1,5,1) is 1,2,3,4.

Note: range () function returns the range object. So, you need to typecast the range object into
collections.

2.4.1 range () with one argument

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.

Note: By default, the start value is 0 and step value is 1

Syntax:

Figure 2.4.1 range () with one argument

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:

Figure 2.4.2 Range with two arguments

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]

2.4.3. range () with three arguments

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

2.5 for loop:

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:

Figure 2.5(a) Syntax of for loop

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)

2.5.1 Nested for loop

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

Figure 2.5.1(b) Flowchart of nested for loop

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.

2.6 Jump statements

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:

Figure 2.6.1(a) Syntax of break statement


In the above figure, the while loop is used. The statement 1 executes always until the condition
1 is true. Inside the scope of while loop, the if condition is there, if the condition 2 is true, the
control goes to the break statement. Break statement will terminate the while loop and control
moves outside the while loop. And statement 2 will execute.

Flowchart:

Figure 2.6.1(b) Flowchart of break statement


Example:

________________________________________________________________________

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:

Figure 2.6.2(b)Flowchart of continue statement


Example:

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.

2.7 else with loop


2.7.1 While with else statement

In Python, the while statement may have an optional else clause.

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:

Figure 2.7.1(a): Syntax of while loop


Flowchart:

Figure 2.7.1(b): Flowchart of while loop with else clause

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.

Example 1: Without Break Statement


In above example 1, while loop will execute normally up to a given condition. No early exit is
there so else block will be executed.

Example2: With Break Statement

In above example 2, while loop will get terminated when value of condition variable = 3, So else
block will not be executed.

2.7.2 For with else statement:

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.

Figure 2.7.2(a) Execution of for-else


Syntax:

Figure 2.7.2(b) Syntax of for else

Flow chart:

Figure 2.7.2(c) Flowchart of for else

Example 1: Demonstration of for loop with else


In this example, for loop has been used with else, we can clearly see that, first all the elements
of sequence get executed and when all values from 0 to 4 gets printed, control goes to else part
of the program.

Example 2: Demonstration of for loop with break and else

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:

1. Write a program to check if given input number is Armstrong number or not


2. Write a program using for, else and break for a company.
a. Criteria is to shortlist 5 students based on percentage 75%
b. Total candidates are 20
c. If shortlisted candidates are less than 5, program should print not enough
eligible
References:
1. https://docs.python.org/3/tutorial/controlflow.html
2. Think Python: An Introduction to Software Design, Book by Allen B. Downey
3. Head First Python, 2nd Edition, by Paul Barry
4. Python Basics: A Practical Introduction to Python, by David Amos, Dan Bader, Joanna
Jablonski, Fletcher Heisler
5. https://fresh2refresh.com/python-tutorial/python-jump-statements/
6. https://tutorialsclass.com/python-jump-statements/

You might also like