Skip to main content
Python Control Structure
by
S.P. Siddique Ibrahim
AP/CSE
Kumaraguru College ofTechnology
Coimbatore
1
IntroductionIntroduction
Says the control flow of the statement in
the programming language.
Show the control flow
2
Control StructuresControl Structures
3 control structures
◦ Sequential structure
 Built into Python
◦ Decision/ Selection structure
 The if statement
 The if/else statement
 The if/elif/else statement
◦ Repetition structure / Iterative
 The while repetition structure
 The for repetition structure
3
4
Sequential StructureSequential Structure
Normal flow/sequential execution of the
statement.
Line by line/Normal execution
If you want to perform simple addition:
A=5
B=6
Print(A+B)
5
Sequence Control StructureSequence Control Structure
6
Fig. 3.1 Sequence structure flowchart with pseudo code.
add grade to total
add 1 to counter
total = total + grade;
counter = counter + 1;
Decision Control flowDecision Control flow
There will be a condition and based on
the condition parameter then the control
will be flow in only one direction.
7
8
9
10
11
ifif Selection StructureSelection Structure
12
Fig. 3.3 if single-selection structure flowchart.
print “Passed”Grade >= 60
true
false
13
14
15
16
17
Control StructuresControl Structures
18
 >>> x = 0
 >>> y = 5
 >>> if x < y: # Truthy
 ... print('yes')
 ...
 yes
 >>> if y < x: # Falsy
 ... print('yes')
 ...
 >>> if x: # Falsy
 ... print('yes')
 ...
 >>> if y: # Truthy
 ... print('yes')
 ...
 yes
 >>> if x or y: # Truthy
 ... print('yes')
 ...
 yes
19
 >>> if x and y: # Falsy
 ... print('yes')
 ...
 >>> if 'aul' in 'grault': # Truthy
 ... print('yes')
 ...
 yes
 >>> if 'quux' in ['foo', 'bar', 'baz']: # Falsy
 ... print('yes')
20
If else:If else:
21
if/elseif/else StructureStructure
22
Fig. 3.4 if/else double-selection structure flowchart.
Grade >= 60
print “Passed”print “Failed”
false true
23
Class ActivityClass Activity
# Program checks if the number is
positive or negative and displays an
appropriate message
# Program checks if the number is
positive or negative –Get the input from
the user also checks the zero inside the
positive value
24
num = 3
# Try these two variations as well.
# num = -5
# num = 0
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
25
Contd.,Contd.,
26
if/elif/elseif/elif/else SelectionSelection
StructureStructure
27
condition a
true
false
.
.
.
false
false
condition z
default action(s)
true
true
condition b
case a action(s)
case b action(s)
case z action(s)
if statement
first elif
statement
last elif
statement
else
statement
Fig. 3.5 if/elif/else multiple-selection structure.
syntaxsyntax
28
Example Python codeExample Python code
29
Example with Python codeExample with Python code
30
# get price from user and convert it into a float:
price = float( raw_input(“Enter the price of one tomato: “))
if price < 1:
s = “That’s cheap, buy a lot!”
elif price < 3:
s = “Okay, buy a few”
else:
s = “Too much, buy some carrots instead”
print s
Control StructuresControl Structures
31
32
3.73.7 whilewhile Repetition StructureRepetition Structure
33
true
false
Product = 2 * productProduct <= 1000
Fig. 3.8 while repetition structure flowchart.
When we login to our homepage on Facebook, we have about 10
stories loaded on our newsfeed
As soon as we reach the end of the page, Facebook loads another 10
stories onto our newsfeed
This demonstrates how ‘while’ loop can be used to achieve this
34
35
36
37
Listing ‘Friends’ from your profile will display the names and photos of all of
your friends
To achieve this, Facebook gets your ‘friendlist’ list containing all the profiles of
your friends
Facebook then starts displaying the HTML of all the profiles till the list index
reaches ‘NULL’
The action of populating all the profiles onto your page is controlled by ‘for’
statement
38
3.133.13 forfor Repetition StructureRepetition Structure
The for loop
◦ Function range is used to create a list of values
 range ( integer )
 Values go from 0 up to given integer (i.e., not including)
 range ( integer, integer )
 Values go from first up to second integer
 range ( integer, integer, integer )
 Values go from first up to second integer but increases in intervals
of the third integer
◦ This loop will execute howmany times:
for counter in range ( howmany ):
and counter will have values 0, 1,..
howmany-1
39
for counter in range(10):
print (counter)
Output?
40
41
42
43
44
45
# Prints out 0,1,2,3,4
count = 0
while True:
 print(count)
 count += 1
 if count >= 5:
 break
# Prints out only odd numbers - 1,3,5,7,9
for x in range(10): # Check if x is even
 if x % 2 == 0:
 continue
 print(x)
46
47
Example for PassExample for Pass
48
Expression values?Expression values?
49
Python 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> if 0:
... print "0 is true"
... else:
... print "0 is false"
...
0 is false
>>> if 1:
... print "non-zero is true"
...
non-zero is true
>>> if -1:
... print "non-zero is true"
...
non-zero is true
>>> print 2 < 3
1
Expressions have integer values. No true, false like in Java.
0 is false, non-0 is true.
3.16 Logical Operators3.16 Logical Operators
Operators
◦ and
 Binary. Evaluates to true if both expressions are true
◦ or
 Binary. Evaluates to true if at least one expression is
true
◦ not
 Unary. Returns true if the expression is false
50
Compare with &&, || and ! in Java
Logical operatorsLogical operators andand,, oror,, notnot
51
if gender == “female” and age >= 65:
seniorfemales = seniorfemales + 1
if iq > 250 or iq < 20:
strangevalues = strangevalues + 1
if not found_what_we_need:
print “didn’t find item”
# NB: can also use !=
if i != j:
print “Different values”
ExampleExample
52
3.11 Augmented Assignment3.11 Augmented Assignment
SymbolsSymbols
Augmented addition assignment symbols
◦ x = x + 5 is the same as x += 5
◦ Can’t use ++ like in Java!
Other math signs
◦ The same rule applies to any other
mathematical symbol
*, **, /, %
53
KeywordsKeywords
54
Python
keywords
and continue else for import not raise
assert def except from in or return
break del exec global is pass try
class elif finally if lambda print while
Fig. 3.2 Python keywords.
Can’t use as identifiers
keywordkeyword passpass : do nothing: do nothing
55
Python 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> if 1 < 2:
... pass
...
Sometimes useful, e.g. during development:
if a <= 5 and c <= 5:
print “Oh no, both below 5! Fix problem”
if a > 5 and c <= 5:
pass # figure out what to do later
if a <= 5 and c > 5:
pass # figure out what to do later
if a > 5 and c > 5:
pass # figure out what to do later
Program OutputProgram Output
1 # Fig. 3.10: fig03_10.py
2 # Class average program with counter-controlled repetition.
3
4 # initialization phase
5 total = 0 # sum of grades
6 gradeCounter = 1 # number of grades entered
7
8 # processing phase
9 while gradeCounter <= 10: # loop 10 times
10 grade = raw_input( "Enter grade: " ) # get one grade
11 grade = int( grade ) # convert string to an integer
12 total = total + grade
13 gradeCounter = gradeCounter + 1
14
15 # termination phase
16 average = total / 10 # integer division
17 print "Class average is", average
56
Enter grade: 98
Enter grade: 76
Enter grade: 71
Enter grade: 87
Enter grade: 83
Enter grade: 90
Enter grade: 57
Enter grade: 79
Enter grade: 82
Enter grade: 94
Class average is 81
The total and counter, set to
zero and one respectively
A loop the continues as long as
the counter does not go past 10
Adds one to the counter to
eventually break the loop
Divides the total by the 10
to get the class average
Program OutputProgram Output1 # Fig. 3.22: fig03_22.py
2 # Summation with for.
3
4 sum = 0
5
6 for number in range( 2, 101, 2 ):
7 sum += number
8
9 print "Sum is", sum
57
Sum is 2550
Loops from 2 to 101
in increments of 2
A sum of all the even
numbers from 2 to 100
Another example
Program OutputProgram Output
1 # Fig. 3.23: fig03_23.py
2 # Calculating compound interest.
3
4 principal = 1000.0 # starting principal
5 rate = .05 # interest rate
6
7 print "Year %21s" % "Amount on deposit"
8
9 for year in range( 1, 11 ):
10 amount = principal * ( 1.0 + rate ) ** year
11 print "%4d%21.2f" % ( year, amount )
58
Year Amount on deposit
1 1050.00
2 1102.50
3 1157.63
4 1215.51
5 1276.28
6 1340.10
7 1407.10
8 1477.46
9 1551.33
10 1628.89
1.0 + rate is the same no matter
what, therefore it should have been
calculated outside of the loop
Starts the loop at 1 and goes to 10
Program OutputProgram Output
1 # Fig. 3.24: fig03_24.py
2 # Using the break statement in a for structure.
3
4 for x in range( 1, 11 ):
5
6 if x == 5:
7 break
8
9 print x,
10
11 print "nBroke out of loop at x =", x
59
1 2 3 4
Broke out of loop at x = 5
Shows that the counter does not get
to 10 like it normally would have
When x equals 5 the loop breaks.
Only up to 4 will be displayed
The loop will go from 1 to 10
Program OutputProgram Output
1 # Fig. 3.26: fig03_26.py
2 # Using the continue statement in a for/in structure.
3
4 for x in range( 1, 11 ):
5
6 if x == 5:
7 continue
8
9 print x,
10
11 print "nUsed continue to skip printing the value 5"
60
1 2 3 4 6 7 8 9 10
Used continue to skip printing the value 5
The value 5 will never be
output but all the others will
The loop will continue
if the value equals 5
continue skips rest of body but continues loop
Advantage of PythonAdvantage of Python
61
62