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

Py4Inf 03 Conditional

Uploaded by

junedijoasli
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Py4Inf 03 Conditional

Uploaded by

junedijoasli
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Conditional Execution

Chapter 3

Python for Informatics: Exploring Information


www.py4inf.com
Unless otherwise noted, the content of this course material is licensed under a Creative
Commons Attribution 3.0 License.
http://creativecommons.org/licenses/by/3.0/.

Copyright 2010,2011 Charles R. Severance


x=5
Conditional Steps
Yes
X < 10 ? Program:

print 'Smaller' x=5 Output:


if x < 10:
print 'Smaller' Smaller
Yes
X > 20 ? Finis
if x > 20:
print 'Bigger' print 'Bigger'

print 'Finis'
print 'Finis'
Comparison Operators
• Boolean expressions ask a
Python Meaning
question and produce a Yes or
No result which we use to < Less than
control program flow <= Less than or Equal
== Equal to
• Boolean expressions using >= Greater than or Equal
comparison operators evaluate
> Greater than
to - True / False - Yes / No
!= Not equal
• Comparison operators look at
variables but do not change the
variables Remember: “=” is used for assignment.

http://en.wikipedia.org/wiki/George_Boole
x=5
if x == 5 : Comparison
print 'Equals 5'
Operators
if x > 4 :
print 'Greater than 4'
if x >= 5 : Equals 5
print 'Greater than or Equal 5' Greater than 4
Greater than or Equal 5
if x < 6 : print 'Less than 6' Less than 6
Less than or Equal 5
if x <= 5 : Not equal 6
print 'Less than or Equal 5'
if x != 6 :
print 'Not equal 6'
Boolean Operations

• We can do calculations with boolean variables just like with integer


variables

• The boolean operations are: and or not

• Comparison operators < > <= >= == != return boolean (True or


False)
Boolean Operators
P Q P and Q P not P
T T T
(x == 4) or (y == 2) T F
F T F
F T
T F F
Evaluates to true if either
F F F
expression is true. not ( x == 4)
( x == 4 ) and (y ==2) P Q P or Q Not “flips” the logic
T T T - True becomes
True if both expressions F T T False and False
are true.
T F T becomes True.
F F F
x=5
print 'Before 5'
Yes
if x == 5 : X == 5 ?
print 'Is 5'
print 'Is Still 5' Before 5 No print 'Is 5'
print 'Third 5' Is 5
Is Still 5 print 'Still 5'
print 'Afterwards 5' Third 5
Afterwards 5 print 'Third 5'
print 'Before 6' Before 6
if x == 6 : Afterwards 6
print 'Is 6'
print 'Is Still 6'
print 'Third 6'

print 'Afterwards 6'


One-Way Decisions
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 to 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 w.r.t. indentation


Warning: Turn Off Tabs
• Most text editors can turn tabs into spaces - make sure to enable this
feature

• NotePad++: Settings -> Preferences -> Language Menu/Tab Settings

• TextWrangler: TextWrangler -> Preferences -> Editor Defaults

• Python cares a *lot* about how far line is indented. If you mix tabs
and spaces, you may get “indentation errors” even if everything looks
fine

Please do this now while you are thinking about it so we can all stay sane...
This will save you
much unnecessary
pain.
increase / maintain after if or for
decrease to indicate end of block
blank lines and comment lines ignored
x=5
x=5
if x > 2 :
if x > 2 :
# comments
print 'Bigger than 2'
print 'Still bigger'
print 'Bigger than 2'
print 'Done with 2'
# don’t matter
print 'Still bigger'
for i in range(5) :
# but can confuse you
print i
if i > 2 :
print 'Done with 2'
print 'Bigger than 2'
# if you don’t line
print 'Done with i', i
# them up
Mental begin/end squares
x=5 x=5
if x > 2 : if x > 2 :
print 'Bigger than 2' # comments
print 'Still bigger'
print 'Done with 2' print 'Bigger than 2'
# don’t matter
for i in range(5) : print 'Still bigger'
print i # but can confuse you
if i > 2 :
print 'Bigger than 2' print 'Done with 2'
print 'Done with i', i # if you don’t line
# them up
yes
Nested x>1

Decisions no print 'More than one'

x = 42
yes
if x > 1 : x < 100

print 'More than one' no


if x < 100 : print 'Less than 100'

print 'Less than 100'

print 'All done'


print 'All Done'
yes
Nested x>1

Decisions no print 'More than one'

x = 42
yes
if x > 1 : x < 100

print 'More than one' no


if x < 100 : print 'Less than 100'

print 'Less than 100'

print 'All done'


print 'All Done'
yes
Nested x>1

Decisions no print 'More than one'

x = 42
yes
if x > 1 : x < 100

print 'More than one' no


if x < 100 : print 'Less than 100'

print 'Less than 100'

print 'All done'


print 'All Done'
Two Way
Decisions X=4

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

• It is like a fork in the


road - we must choose
one or the other path print 'All Done'
but not both
Two-way
using else :
X=4

no yes
x=4 x>2

if x > 2 :
print 'Smaller' print 'Bigger'
print 'Bigger'
else :
print 'Smaller'
print 'All Done'
print 'All done'
Two-way
using else :
X=4

no yes
x=4 x>2

if x > 2 :
print 'Smaller' print 'Bigger'
print 'Bigger'
else :
print 'Smaller'
print 'All Done'
print 'All done'
Multi-way
yes
x<2 print 'Small'
if x < 2 : no
print 'Small'
yes
elif x < 10 :
x<10 print 'Medium'
print 'Medium' no
else :
print 'LARGE' print 'LARGE'
print 'All done'

print 'All Done'


Multi-way X=0

yes
x<2 print 'Small'
x=0 no
if x < 2 : yes
print 'Small' x<10 print 'Medium'
elif x < 10 : no
print 'Medium'
else : print 'LARGE'
print 'LARGE'
print 'All done'
print 'All Done'
Multi-way X=5

yes
x<2 print 'Small'
x=5 no
if x < 2 : yes
print 'Small' x<10 print 'Medium'
elif x < 10 : no
print 'Medium'
else : print 'LARGE'
print 'LARGE'
print 'All done'
print 'All Done'
Multi-way X = 20

yes
x<2 print 'Small'
x = 20 no
if x < 2 : yes
print 'Small' x<10 print 'Medium'
elif x < 10 : no
print 'Medium'
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'
Multi-way Puzzles
Which will never print? if x < 2 :
print 'Below 2'
if x < 2 : elif x < 20 :
print 'Below 2' print 'Below 20'
elif x >= 2 : elif x < 10 :
print 'Two or more' print 'Below 10'
else : else :
print 'Something else' print 'Something else'
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


$ cat notry.py
astr = 'Hello Bob' $ python notry.py
istr = int(astr) Traceback (most recent call last):
The print 'First', istr File "notry.py", line 6, in <module>
program istr = int(astr)
stops astr = '123' ValueError: invalid literal for int() with
here istr = int(astr) base 10: 'Hello Bob'
print 'Second', istr
All
Done
Generic
Software Computer
Input
Central
Devices
Processing
Unit
Secondary
Memory

Output Main
Devices Memory
$ cat tryexcept.py
astr = 'Hello Bob' When the first conversion fails - it
try: just drops into the except: clause and
istr = int(astr) the program continues.
except:
istr = -1
$ python tryexcept.py
print 'First', istr
First -1
Second 123
astr = '123'
try:
istr = int(astr) When the second conversion
except: succeeds - it just skips the except:
istr = -1 clause and the program continues.

print 'Second', istr


try / except astr = 'Bob'

print 'Hello'
astr = 'Bob'
try:
print 'Hello' istr = int(astr)
istr = int(astr)
print 'There' print 'There'
except:
istr = -1 istr = -1

print 'Done', istr print 'Done', istr Safety net


Sample try / except
rawstr = raw_input('Enter a number:')

try:
$ python trynum.py
ival = int(rawstr)
Enter a number:42
except:
Nice work
ival = -1
$ python trynum.py
Enter a number:fourtytwo
if ival > 0 :
Not a number
print 'Nice work'
$
else:
print 'Not a number'
Exercise

Rewrite your pay computation to give the employee


1.5 times the hourly rate for hours worked above 40
hours.

Enter Hours: 45
Enter Rate: 10
Pay: 475.0

475 = 40 * 10 + 5 * 15
Exercise
Rewrite your pay program using try and except so
that your program handles non-numeric input
gracefully.

Enter Hours: 20
Enter Rate: nine
Error, please enter numeric input

Enter Hours: forty


Error, please enter numeric input
Summary
• Comparison operators == <= • Two way Decisions if : and else :
>= > < !=
• Nested Decisions
• Logical operators: and or not
• Multiway decisions using elif
• Indentation
• Try / Except to compensate for
• One Way Decisions errors

• Short circuit evaluations

You might also like