Python Content ManualII-TE
Python Content ManualII-TE
In the programs we have seen till now, there has always been a series of statements
faithfully executed by Python in exact top-down order. What if you wanted to change the flow
of how it works? For example, you want the program to take some decisions and do different
things depending on different situations, such as printing 'Good Morning' or 'Good Evening'
depending on the time of the day?
As you might have guessed, this is achieved using control flow statements. There are three
control flow statements in Python - if, for and while.
Flow of
Control and
Conditions
While
If Statement For Statement
Statement
If Statement
On the occasion of World Health Day, one of the schools in the city decided to take
an initiative to help students maintain their health and be fit. Let’s observe an
interesting conversation happening between the students when they come to know
about the initiative.
75
There come situations in real life when we need to make some decisions and based on
these decisions, we need to decide what should we do next. Similar situations arise in
programming also where we need to make some decisions and based on these decisions
we will execute the next block of code.
● if statement
● if..else statements
● if-elif ladder
76
If Statement
The if statement is used to check a condition: if the condition is true, we run a block of
statements (called the if-block).
Syntax:
if test expression:
statement(s)
Here, the program evaluates the test expression and will execute statement(s) only if the text
expression is True.
Note:
1) In Python, the body of the if statement is indicated by the indentation. Body starts with
an indentation and the first unindented line marks the end.
2) Python interprets non-zero values as True. None and 0 are interpreted as False.
77
Example :
num = 3
if num > 0:
print(num, “is a positive number.”)
print(“this is always printed”)
num = -1
if num > 0:
print(num, “is a positive number.”)
print(“this is always printed”)
3 is a positive number
This is always printed
This is also always printed.
In the above example, num > 0 is the test expression. The body of if is executed only if this
evaluates to True.
When variable num is equal to 3, test expression is true and body inside body of if is
executed.
If variable num is equal to -1, test expression is false and body inside body of if is skipped.
The print() statement falls outside of the if block (unindented). Hence, it is executed
regardless of the test expression.
Syntax of if...else
if test expression:
Body of if
else:
Body of else
The if..else statement evaluates test expression and will execute body of if only when test
condition is True.
If the condition is False, body of else is executed. Indentation is used to separate the blocks.
78
Python if..else Flowchart
Example of if...else
In the above example, when if the age entered by the person is greater than or equal to 18,
he/she can vote. Otherwise, the person is not eligible to vote
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
The elif is short for else if. It allows us to check for multiple expressions.
If the condition for if is False, it checks the condition of the next elif block and so on.
79
Only one block among the several if...elif...else blocks is executed according to the
condition.
The if block can have only one else block. But it can have multiple elif blocks.
Flowchart of if...elif...else
Example of if...elif...else
Marks = 60
80
Python Nested if statements
We can have an if...elif...else statement inside another if...elif...else statement. This is called
nesting in computer programming.
Any number of these statements can be nested inside one another. Indentation is the only
way to figure out the level of nesting. This can get confusing, so must be avoided if it can be.
Output 1
Enter a number: 5
Positive number
Output 2
Enter a number: -1
Negative number
Output 3
Enter a number: 0
Zero
Let’s Practice
Let’s Go through the If-Else Jupyter Notebook to get an experiential learning experience for
If-Else. To download the Jupyter Notebook, go to the following link : http://bit.ly/ifelse_jupyter
Note:
To open Jupyter notebook, go to start menu → open anaconda prompt → write “jupyter
notebook”
81
The For Loop
The for..in statement is another looping statement which iterates over a sequence of objects
i.e. go through each item in a sequence. We will see more about sequences in detail in later
chapters. What you need to know right now is that a sequence is just an ordered collection
of items.
Here, val is the variable that takes the value of the item inside the sequence on each
iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is
separated from the rest of the code using indentation.
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
82
# variable to store the sum
sum = 0
The sum is 48
The while statement allows you to repeatedly execute a block of statements as long as a
condition is true. A while statement is an example of what is called a looping statement.
A while statement can have an optional else clause.
while test_expression:
Body of while
In while loop, test expression is checked first. The body of the loop is entered only if
the test_expression evaluates to True. After one iteration, the test expression is checked
again. This process continues until the test_expression evaluates to False. In Python, the
body of the while loop is determined through indentation. Body starts with indentation and
the first unindented line marks the end. Python interprets any non-zero value
as True. None and 0 are interpreted as False.
83
Flowchart of while Loop
n = 10
while i <= n:
sum = sum + i
i = i+1 # update counter
Enter n: 10
The sum is 55
In the above program, the test expression will be True as long as our counter variable i is
less than or equal to n (10 in our program).
84
We need to increase the value of the counter variable in the body of the loop. This is very
important (and mostly forgotten). Failing to do so will result in an infinite loop (never ending
loop).
Let’s Practice
Let’s Go through the flow control Jupyter Notebook to get an experiential learning
experience for ‘for’ and ‘while’ loop . To download the Jupyter Notebook, go to the following
link : http://bit.ly/loops_jupyter
Note:
To open Jupyter notebook, go to start menu → open anaconda prompt → write “jupyter
notebook”
85