0% found this document useful (0 votes)
28 views11 pages

Python Content ManualII-TE

Uploaded by

Nageswar C
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views11 pages

Python Content ManualII-TE

Uploaded by

Nageswar C
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Chapter 5 - Flow of Control and Conditions

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.

Decision making statements in programming languages decide the direction of flow of


program execution. Decision making statements available in Python are:

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

If the text expression is False, the statement(s) is not executed.

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.

Python if Statement Flowchart

77
Example :

#Check if the number is positive, we print an appropriate message

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

When you run the program, the output will be:

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.

Python if...else Statement

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

#A program to check if a person can vote

age = input(“Enter Your Age”)

if age >= 18:


print(“You are eligible to vote”)
else:
print(“You are not eligible to vote”)

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

Python if...elif...else Statement


Syntax of if...elif...else

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.

If all the conditions are False, body of else is executed.

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

#To check the grade of a student

Marks = 60

if marks > 75:


print("You get an A grade")
elif marks > 60:
print("You get a B grade")
else:
print("You get a C grade")

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.

Python Nested if Example

# In this program, we input a number


# check if the number is positive or
# negative or zero and display
# an appropriate message
# This time we use nested if

num = float(input("Enter a number: "))


if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")

When you run the above program

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.

Syntax of for Loop

for val in sequence:


Body of for

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.

Flowchart of for Loop

Example: Python for Loop


# Program to find the sum of all numbers stored in a list

# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]

82
# variable to store the sum
sum = 0

# iterate over the list


for val in numbers:
sum = sum+val

# Output: The sum is 48


print("The sum is", sum)

when you run the program, the output will be:

The sum is 48

The while Statement

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.

Syntax of while Loop in Python

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

Example: Python while Loop


# Program to add natural
# numbers upto
# sum = 1+2+3+...+n

# To take input from the user,


# n = int(input("Enter n: "))

n = 10

# initialize sum and counter


sum = 0
i = 1

while i <= n:
sum = sum + i
i = i+1 # update counter

# print the sum


print("The sum is", sum)

When you run the program, the output will be:

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

Finally, the result is displayed.

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”

Test Your Knowledge


Q1) Explain different types of 'If' statements with the help of a flowchart.
Q2) What is the difference between 'for' loop and 'while' loop. Explain with a help of a
flowchart?
Q3) What are python nested if statements? Explain with example.
Q4) Write a program to find numbers which are divisible by 7 and multiple of 5 between 1200
and 2200.
Q5) Write a program to find the whether a number is prime or not using 'while' loop.

85

You might also like