0% found this document useful (0 votes)
137 views

Python Control Structures - 2

The document discusses different types of control flow in Python programs including sequential, conditional, and repetitive flow. It provides examples of conditional statements using comparison operators like ==, <, > to direct program execution. Specifically, it demonstrates if/else statements for two-way decisions and elif for multi-way decisions. The document also covers indentation, nested conditional blocks, and the try/except structure for handling errors or exceptions.

Uploaded by

Harinath Pspk
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)
137 views

Python Control Structures - 2

The document discusses different types of control flow in Python programs including sequential, conditional, and repetitive flow. It provides examples of conditional statements using comparison operators like ==, <, > to direct program execution. Specifically, it demonstrates if/else statements for two-way decisions and elif for multi-way decisions. The document also covers indentation, nested conditional blocks, and the try/except structure for handling errors or exceptions.

Uploaded by

Harinath Pspk
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/ 30

Python : Control Structures

Types of Flow in a Program


• There are Three Main Types of a flow in a computer program
Sequential : in which instructions are executed successfully

Conditional : in which certain block of statements are executed if the


condition is True or False correspondingly

Repetition : in which a block of statements are repeated over a


collection of objects or until a specific condition is met.
x=5
Conditional Steps
Yes
x < 10 ?

No print('Smaller') Program:
Output:
x = 5
Yes if x < 10: Smaller
x > 20 ? print('Smaller') Finis
if x > 20:
No print('Bigger') print('Bigger')

print('Finis')

print('Finis')
Comparison Operators
• Boolean expressions ask a Python Meaning
question and produce a Yes or No < Less than
result which we use to control
program flow <= Less than or Equal to
== Equal to
• Boolean expressions using >= Greater than or Equal to
comparison operators evaluate to
> Greater than
True / False or Yes / No
!= Not equal
• Comparison operators look at
variables but do not change the Remember: “=” is used for assignment.
variables
http://en.wikipedia.org/wiki/George_Boole
Comparison Operators
x = 5
if x == 5 :
print('Equals 5') Equals 5
if x > 4 :
print('Greater than 4') Greater than 4
if x >= 5 :
Greater than or Equals 5
print('Greater than or Equals 5')
if x < 6 : print('Less than 6') Less than 6
if x <= 5 :
print('Less than or Equals 5') Less than or Equals 5
if x != 6 :
print('Not equal 6') Not equal 6
One-Way Decisions
x = 5 Yes
print('Before 5') Before 5 x == 5 ?
if x == 5 :
print('Is 5') Is 5 print('Is 5’)
No
print('Is Still 5')
Is Still 5
print('Third 5')
print('Afterwards 5')
Third 5 print('Still 5')
print('Before 6') Afterwards 5
if x == 6 : Before 6 print('Third 5')
print('Is 6')
print('Is Still 6')
print('Third 6')
print('Afterwards 6') Afterwards 6
Indentation
• Increase indent indent after an if statement or for statement (after : )

• Maintain indent to indicate the scope of the block (which lines are affected
by the if/for)

• Reduce indent back to the level of the if statement or for statement to


indicate the end of the block

• Blank lines are ignored - they do not affect indentation

• Comments on a line by themselves are ignored with regard to indentation


Think About begin/end Blocks
x = 5
if x > 2 :
print('Bigger than 2')
print('Still bigger')
print('Done with 2')

for i in range(5) :
print(i)
if i > 2 :
print('Bigger than 2')
print('Done with i', i)
print('All Done')
Nested x>1
yes

Decisions n
o print('More than one’)

x = 42
if x > 1 : yes
print('More than one') x < 100
if x < 100 : n
print('Less than 100') o print('Less than 100')
print('All done')

print('All Done')
Two-way Decisions
x=4

• Sometimes we want to
do one thing if a logical no yes
x>2
expression is true and
something else if the
expression is false print('Not bigger') print('Bigger')

• It is like a fork in the


road - we must choose
one or the other path but print('All Done')
not both
Two-way Decisions
x=4
with else:
no yes
x = 4 x>2

if x > 2 :
print('Bigger') print('Not bigger') print('Bigger')
else :
print('Smaller')

print('All done')
print('All Done')
Multi-way
yes
x<2 print('small')
no
if x < 2 :
yes
print('small')
elif x < 10 :
x < 10 print('Medium')
print('Medium') no
else :
print('LARGE') print('LARGE')
print('All done')

print('All Done')
x=0
Multi-way
yes
x<2 print('small')
x = 0
no
if x < 2 :
yes
print('small')
elif x < 10 :
x < 10 print('Medium')
print('Medium') no
else :
print('LARGE') print('LARGE')
print('All done')

print('All Done')
x=5
Multi-way
yes
x<2 print('small')
x = 5
no
if x < 2 :
yes
print('small')
elif x < 10 :
x < 10 print('Medium')
print('Medium') no
else :
print('LARGE') print('LARGE')
print('All done')

print('All Done')
x = 20
Multi-way
yes
x<2 print('small')
x = 20
no
if x < 2 :
yes
print('small')
elif x < 10 :
x < 10 print('Medium')
print('Medium') no
else :
print('LARGE') print('LARGE')
print('All done')

print('All Done')
Multi-way if x < 2 :
print('Small')
elif x < 10 :
# No Else print('Medium')
x = 5 elif x < 20 :
if x < 2 : print('Big')
print('Small') elif x < 40 :
elif x < 10 : print('Large')
print('Medium') elif x < 100:
print('Huge')
print('All done') else :
print('Ginormous')
Another if form – Conditional Expression
• An alternative if form returns a value – Python Version
of Ternary Operator
• 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’
The try / except Structure

• You surround a dangerous section of code with try and except


• If the code in the try works - the except is skipped
• If the code in the try fails - it jumps to the except section
$ python3 notry.py
Traceback (most recent call last):
File "notry.py", line 2, in <module>
istr = int(astr)ValueError: invalid literal
for int() with base 10: 'Hello Bob'
$ cat notry.py
astr = 'Hello Bob' All
istr = int(astr) Done
print('First', istr)
astr = '123'
istr = int(astr)
print('Second', istr)
$ python3 notry.py
Traceback (most recent call last):
File "notry.py", line 2, in <module>
The istr = int(astr)ValueError: invalid literal
program for int() with base 10: 'Hello Bob'
stops $ cat notry.py
here astr = 'Hello Bob' All
istr = int(astr) Done
print('First', istr)
astr = '123'
istr = int(astr)
print('Second', istr)
astr = 'Hello Bob' When the first conversion fails - it
try: just drops into the except: clause
istr = int(astr) and the program continues.
except:
istr = -1
$ python tryexcept.py
print('First', istr) First -1
Second 123
astr = '123'
try:
istr = int(astr)
except:
istr = -1 When the second conversion
succeeds - it just skips the except:
print('Second', istr) clause and the program continues.
astr = 'Bob'
try / except
print('Hello')
astr = 'Bob'
try:
print('Hello') istr = int(astr)
istr = int(astr)
print('There')
except: print('There')
istr = -1
istr = -1
print('Done', istr)

print('Done', istr) Safety net


Sample try / except
rawstr = input('Enter a number:')
try:
ival = int(rawstr) $ python3 trynum.py
except: Enter a number:42
ival = -1 Nice work
$ python3 trynum.py
if ival > 0 : Enter a number:forty-two
print('Nice work') Not a number
else: $
print('Not a number')
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"

>>>
For Loops

• 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 & 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
>>>
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.
Usage of ‘else’ in Loops
• Else part can be included in with both ‘for’ and ‘while’ constructs.

• Else block will be executed once the repletion is done for the given
collection of objects/condition is failed

• Else block will only be executed if loops exits without the occurrence of
break statement.

You might also like