KEMBAR78
Python Programming - Control Flow | PDF
CS.QIAU - Winter 2020
PYTHONControl Flow - Session 2
Omid AmirGhiasvand
Programming
Control Flow Statements/Structure
▸ Python supports a set of control flow statements that you can integrate
into your program
▸ Sequential
▸ Line by line from top to bottom execution of statement in the same order they
appear in the program
▸ Decision
▸ Allows conditionally execute or not execute a block of code.
▸ Loop
▸ Allow the execution of a block of statement multiple time.
Condition/if Statement
Repetition/ Iteration Statement
If Control Flow Statement
if boolean_expression :
statement-1
statement-2
statement-3
else :
statement-4
keyword
block of Code
colon
keyword
another
block
None is a
special value and
also a data typeboolean
expression
using is
operator
check the
string if it contain a
number
now we
can cast to int
remove the
str & see what will
happen
remove
return & see what
will happen
first
else statement
line 14
▸ We can as many as elif we want.
If Control Flow Statement
if boolean_expression-1 :
statement-1
statement-2
elif boolean_expression-2 :
statement-3
statement-4
elif boolean_expression-3 :
statement-5
else :
statement-6
keyword
to distinguish
None and False
it is correct
BUT
much simpler
Nested if Statements
▸ We can place an if statement inside another if statement.
if boolean_expression-1 :
if boolean_expression-2
statement-1
else
statement-2
elif boolean_expression-3 :
statement-3
else :
statement-4
will match
the closest if
match to
closest if statement
while boolean_expresion :
statement-1
statement-2
statement-3
While Control Flow Statement
block of Code
keyword
colon
iterate
while True
a boolean
expression
while continue
until user enter a
number
a number entered
what happened!?
17 is a number! isn’t it ?
BE CAREFUL ABOUT
INFINITE LOOP
update loop
control variable inside
the loop body
For Control Flow Statement
for iteration_variable in sequence:
statement-1
statement-2
statement-3
Block of Code
keyword Colon
sequence
of items
keyworditem
range is a built-
in function
remove end=‘, ‘
and see what will
happen
super easy program but the
details are always important
you can write
this program in 100
ways
here we did
not check user
input. but we have
to!
Break and Continue
▸ If you wand to loop until something occurs, but you’re not sure when
that might happen, you can use an infinite loop with a break statement.
▸ If you don’t want to break out of a loop but just want to skip ahead to
the next iteration for some reason you can use continue statement.
skip 3
“The Unexamined Life Is Not Worth Living”

Python Programming - Control Flow