Python Control
of Flow
Python Control Flow
statements
There are three control flow statements in
Python - if, for and while.
Decision making statements
Python programming language assumes any non-
zero and non-null values as true and if it is either
zero or null then it is assumed as false value.
Python programming language provides following
types of decision making statements.
Decision making statements
if statements
An if statement consists of a boolean expression
followed by one or more statements.
if...else statements
An if statement can be followed by an optional else
statement, which executes when the boolean
expression is false.
nested if statements
You can use one if or else if statement inside
another if or else if statement(s).
if Statements
if x == 3:
print “X equals 3.”
elif x == 2:
print “X equals 2.”
else:
print “X equals something else.”
print “This is outside the ‘if’.”
Be careful! The keyword if is also used in the
syntax of filtered list comprehensions. Note:
Use of indentation for blocks
Colon (:) after boolean expression
Another if form
An alternative if form returns a value
This can simplify your code
Example:
• return x+1 if x < 0 else x -1
• return ‘hold’ if delta==0 else sell if delta < 0
else ‘buy’
Added in Python v 2.6 (?)
while Loops
>>> x = 3
>>> while x < 5:
print x, "still in the loop"
x = x + 1
3 still in the loop
4 still in the loop
>>> x = 6
>>> while x < 5:
print x, "still in the loop"
>>>
break and continue
You can use the keyword break inside a
loop to leave the while loop entirely.
You can use the keyword continue inside
a loop to stop processing the current
iteration of the loop and to immediately
go on to the next one.
For Loops
For Loops / List Comprehensions
Python’s list comprehensions provide a
natural idiom that usually requires a for-loop in
other programming languages.
• As a result, Python code uses many fewer
for-loops
• Nevertheless, it’s important to learn about
for-loops.
Take care! The keywords for and in are also
used in the syntax of list comprehensions, but
this is a totally different construction.
For Loops 1
A for-loop steps through each of the items in a
collection type, or any other type of object
which is “iterable”
for <item> in <collection>:
<statements>
If <collection> is a list or a tuple, then the loop
steps through each element of the sequence
If <collection> is a string, then the loop steps
through each character of the string
for someChar in “Hello World”:
print someChar
For Loops 2
for <item> in <collection>:
<statements>
<item> can be more than a single variable name
When the <collection> elements are themselves
sequences, then <item> can match the structure
of the elements.
This multiple assignment can make it easier to
access the individual parts of each element
for (x,y) in [(a,1),(b,2),(c,3),(d,4)]:
print x
For loops & the range() function
Since a variable often ranges over some
sequence of numbers, the range() function
returns a list of numbers from 0 up to but not
including the number we pass to it.
range(5) returns [0,1,2,3,4]
So we could say:
for x in range(5):
print x
(There are more complex forms of range() that
provide richer functionality…)
For Loops and Dictionaries
>>> ages = { "Sam" : 4, "Mary" : 3, "Bill" : 2 }
>>> ages
{'Bill': 2, 'Mary': 3, 'Sam': 4}
>>> for name in ages.keys():
print name, ages[name]
Bill 2
Mary 3
Sam 4
>>>
Syntax of if statement
if expression: statement(s)
Single Statement Suites:
If the suite of an if clause consists only of a single line, it may
go on the same line as the header statement.
Here is an example of a one-line if clause:
Indentation
White space is important in Python
White space at the beginning of the line is important, is called
indentation.
Leading whitespace (spaces and tabs) at the beginning of the
logical line (which understand by python) is used to determine
the indentation level of the logical line, which in turn is used to
determine the grouping of statements.
This means that statements which go together must have the
same indentation.
Do not use a mixture of tabs and spaces for the indentation as
it does not work across different platforms properly. It is
strongly recommend that use a single tab or four spaces
Syntax of If-else statement
if expression:
statement(s)
else:
statement(s)
#!/usr/bin/python
var1 = 100
if var1:
print "1 - Got a true expression value"
print var1
else:
print "1 - Got a false expression value"
print var1
The elif Statement
The elif statement allows you to check multiple
expressions for truth value and execute a block of
code as soon as one of the conditions evaluates to
true.
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else: statement(s)
Python does not currently support switch or
case statements as in other languages.
Nested if example
Output
Decision making
while loop
Repeats a statement or group of statements while
a given condition is true. It tests the condition
before executing the loop body.
for loop
Execute a sequence of statements multiple times
and abbreviates the code that manages the loop
variable.
nested loops
You can use one or more loop inside any another
while, for or do..while loop.
While loop example
The else Statement Used with Loops
Python For-loop statements
The for loop in Python has the ability to iterate
over the items of any sequence, such as a
list ,string, tuple and other built-in iterables.
If a sequence contains an expression list, it is evaluated
first. Then, the first item in the sequence is assig ned to the
iterating variable iterating_var. Next, the statements block is
executed. Each item in the list is assig ned to iterating_var,
and the statement(s) block is executed until the entire
sequence is exhausted.
For loop example
#!/usr/bin/python
for letter in 'Python': #example1
print 'Current Letter :', letter
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: #example2
print 'Current fruit :', fruit
print "Good bye!“
for I in range(1,5): #example3
print (i)
else:
print (“The for loop is over”)
Nested loop (print prime
numbers)
Loop Control Statements
break statement
Terminates the loop statement and transfers
execution to the statement immediately following
the loop.
continue statement
Causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating.
pass statement
The pass statement in Python is used when a
statement is required syntactically but you do not
want any command or code to execute.
Break statement example
output
Continue statement example
Pass statement example
for pnum in [1,2, -1, 3]:
if pnum < 0:
pass
else:
print pnum
Output
1
2
3
Exercises
Write a python program to check for validity of
password using if statement
Write a python program to check the eligibility for
voting using if-else
Write a python program to print student garde
using elif
Write a python program to find the factorial of
number using while loop
Write a python program to add 10 numbers by
inputting each from the keyboard using for loop
Write a python program to print string or number
is a palindrome or not.
Steps to install IDLE IDE for
python
For linux / Fedora users
#yum install python-tools
For Ubuntu users
#sudo apt-get install idle