py4inf 03 conditional
TRANSCRIPT
-
8/9/2019 Py4Inf 03 Conditional
1/31
Conditional ExecutionChapte r 3
Python for Informatics: Ex ploring Informati on
www.pythonlearn.com
http://www.pythonlearn.com/http://www.pythonlearn.com/http://www.pythonlearn.com/http://www.pythonlearn.com/http://www.pythonlearn.com/
-
8/9/2019 Py4Inf 03 Conditional
2/31
Conditional StepProgram:
x = 5if x < 10:
print 'Smaller’
if x > 20: print 'Bigger'
print 'Finis'
x = 5
X < 10 ?
print 'Smaller'
X > 20 ?
print 'Bigger'
print 'Finis'
Yes
Yes
No
No
-
8/9/2019 Py4Inf 03 Conditional
3/31
Comparison Operators• Boolean expre ssions ask a
question and produce a Yes orNo result which we use tocontrol program flow
• Boolean expressions usingcomparison operators evaluateto - True / False - Yes / No
• Comparison operators look at variables but do not change thevariables
http://en.wikip edia.org/wiki/George_Boole
Remember: “=” is used for a
Python M< L= Greater
> Gre!= N
http://en.wikipedia.org/wiki/George_Boolehttp://en.wikipedia.org/wiki/George_Boolehttp://en.wikipedia.org/wiki/George_Boolehttp://en.wikipedia.org/wiki/George_Boolehttp://en.wikipedia.org/wiki/George_Boole
-
8/9/2019 Py4Inf 03 Conditional
4/31
Comparison Operators
x = 5if x == 5 :
print 'Equals 5'if x > 4 :
print 'Greater than 4'if x >= 5 : print 'Greater than or Equals 5'if x < 6 : print 'Less than 6'if x
-
8/9/2019 Py4Inf 03 Conditional
5/31
One-Way Decisionsx = 5
print 'Before 5'if x == 5 : print 'Is 5' print 'Is Still 5' print 'Third 5'print 'Afterwards 5’
print 'Before 6’if x == 6 : print 'Is 6' print 'Is Still 6' print 'Third 6'print 'Afterwards 6'
Before 5Is 5Is Still 5Third 5Afterwards5Before 6Afterwards6
X == 5 ?
No
-
8/9/2019 Py4Inf 03 Conditional
6/31
Indentation• Increase indent indent after an if statement or for statement (after
• Maintain indent to indicate the scope of the block (which lines areby the if/ for)
• Reduce indent back to the level of the if statement or for statemenindicate 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 in
-
8/9/2019 Py4Inf 03 Conditional
7/31
Warning : Turn Off Tab• Most text editors can turn tabs into spaces - make sure to enable t
> NotePad++: Settings -> Preferences -> Language Menu/ Tab Set
> TextWrangler: TextWrangler -> Preferences -> Editor Defaults
• Python cares a *lot* about how far a line is indented . If you mixtspaces , you may get “indentation errors ” even if everything looks
Please do this now while you are thinking about it so we can all stay san
-
8/9/2019 Py4Inf 03 Conditional
8/31
This will smuch unnec
pain
-
8/9/2019 Py4Inf 03 Conditional
9/31
x = 5if 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', iprint 'All Done'
increase / maintain after if or fordecrease to indicate end of block
-
8/9/2019 Py4Inf 03 Conditional
10/31
x = 5if 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', iprint 'All Done'
Think about begin/end blocks
-
8/9/2019 Py4Inf 03 Conditional
11/31
x > 1
print 'More than one'
x < 100
pr
print 'All Done'
yes
no
no
x = 42if x > 1 : print 'More than one' if x < 100 :
print 'Less than 100'print 'All done'
NestedDecisions
-
8/9/2019 Py4Inf 03 Conditional
12/31
Two-wayDecisions
• Sometimes we want todo one thing if a logicalexpression is true andsomething else if theexpression is false
• It is like a fork in theroad - we must chooseone or the other pathbut not both
x > 2no
X = 4
print 'Not bigger'
print 'All Done'
-
8/9/2019 Py4Inf 03 Conditional
13/31
Two-wayusing else :
x = 4
if x > 2 : print 'Bigger'else : print 'Smaller'
print 'All done'
x > 2
p
no
x = 4
print 'Smaller'
print 'All Done'
-
8/9/2019 Py4Inf 03 Conditional
14/31
x > 2
p
no
x = 4
print 'Smaller'
print 'All Done'
x = 4
if x > 2 : print 'Bigger'else : print 'Smaller'
print 'All done'
Two-wayusing else :
-
8/9/2019 Py4Inf 03 Conditional
15/31
Multi-way
if x < 2 : print 'small'elif x < 10 : print 'Medium'
else : print 'LARGE'print 'All done'
x < 2 print 'syes
no
print 'All Done'
x < 10 print 'Myes
print 'LARGE'
no
-
8/9/2019 Py4Inf 03 Conditional
16/31
Multi-way
x = 0if x < 2 : print 'small'elif x < 10 : print 'Medium'else : print 'LARGE'print 'All done'
x < 2 print 'sm
yes
no
x = 0
print 'All Done'
x < 10 print 'Meyes
print 'LARGE'no
-
8/9/2019 Py4Inf 03 Conditional
17/31
Multi-way
x = 5if x < 2 : print 'small'elif x < 10 : print 'Medium'else : print 'LARGE'print 'All done'
x < 2 print 'sm
yes
no
x = 5
print 'All Done'
x < 10 print 'Meyes
print 'LARGE'no
-
8/9/2019 Py4Inf 03 Conditional
18/31
Multi-way
x = 20if x < 2 : print 'small'elif x < 10 : print 'Medium'else : print 'LARGE'print 'All done'
x < 2 print 'sm
yes
no
x = 20
print 'All Done'
x < 10 print 'Meyes
print 'LARGE'no
-
8/9/2019 Py4Inf 03 Conditional
19/31
Multi-way
# No Elsex = 5if x < 2 : print 'Small'
elif x < 10 : print 'Medium'
print 'All done'
if x < 2 : print 'Small'elif x < 10 : print 'Medium'elif x < 20 :
print 'Big'elif x < 40 :
print 'Large'
elif x < 100: print 'Huge'else : print 'Ginormous'
-
8/9/2019 Py4Inf 03 Conditional
20/31
Multi-way Puzzles
if x < 2 : print 'Below 2'elif x < 20 : print 'Below 20'elif x < 10 :
print 'Below 10'else : print 'Something else'
if x < 2 : print 'Below 2'elif x >= 2 :
print 'Two or more'else : print 'Something else'
Which will never print?
-
8/9/2019 Py4Inf 03 Conditional
21/31
The try / except Structure
• You surround a dangerous section of code with try and ex
• If the code in the try works - the except is skipped• If the code in the try fails - it jumps to the except section
-
8/9/2019 Py4Inf 03 Conditional
22/31
$ cat notry.pyastr = 'Hello Bob'istr = int(astr)print 'First', istrastr = '123'istr = int(astr)print 'Second', istr
$ python notry.pyTraceback (most recent call File "notry.py", line 2, in
-
8/9/2019 Py4Inf 03 Conditional
23/31
$ python notry.pyTraceback (most recent caFile "notry.py", line 2, in istr = int(astr)ValueError:
for int() with base 10: 'He
Theprogram
stopshere
$ cat notry.pyastr = 'Hello Bob'istr = int(astr)print 'First', istrastr = '123’istr = int(astr)print 'Second', istr
-
8/9/2019 Py4Inf 03 Conditional
24/31
Software
InputDevices Central
ProcessingUnit
MainMemoryOutputDevices
SecondarMemory
GCo
-
8/9/2019 Py4Inf 03 Conditional
25/31
$ cat tryexcept.pyastr = 'Hello Bob'try: istr = int(astr)
except: istr = -1
print 'First', istr
astr = '123'
try: istr = int(astr)except: istr = -1
print 'Second', istr
$ python tryexcept.pyFirst -1
Second 123
When the first conversion just drops into the except
and the program contin
When the second convesucceeds - it just skips thclause and the program co
-
8/9/2019 Py4Inf 03 Conditional
26/31
try / except astr = 'Bob'
astr = 'Bob'try: print 'Hello' istr = int(astr) print 'There'except: istr = -1
print 'Done', istr
print 'Hello'
print 'There'
istr = int(astr)
print 'Done', istr
-
8/9/2019 Py4Inf 03 Conditional
27/31
Sample try / except
$ python trynum.pyEnter a number:Nice work$ python trynum.pyEnter a number:Not a number$
rawstr = raw_input('Enter a number:')try:
ival = int(rawstr)except:
ival = -1
if ival > 0 :print 'Nice work'
else:print 'Not a number'
E i
-
8/9/2019 Py4Inf 03 Conditional
28/31
Exercise
Rewrite your pay computation to give the employee
1.5 times the hourly rate for hours worked above 40hours.
Enter Hours: 45Enter Rate: 10 Pay: 475.0
475 = 40 * 10 +
E i
-
8/9/2019 Py4Inf 03 Conditional
29/31
Exercise
Rewrite your pay program using try and except sothat your program handles non-numeric inputgracefully.
Enter Hours: 20 Enter Rate: nine
Error, please enter numeric inputEnter Hours: forty Error, please enter numeric input
-
8/9/2019 Py4Inf 03 Conditional
30/31
Summary
• Comparison operators== = > < !=
• Logical operators: and or not
• Indentation
• One-way Decisions
• Except to compensate forerrors
• Two-way Decisionsif : and else :
• Nested Decisions
• Multi-way decisions u
elif• Try / Except to compe
for errors
Acknowledgements / Contributions
-
8/9/2019 Py4Inf 03 Conditional
31/31
Acknowledgements / Contributions
These slides are Copyright 2010- Charles R. Severance ( www.dr-chuck.com ) of the University of Michigan School of Informationand open.umich.edu and made available under a CreativeCommons Attribution 4.0 License. Please maintain this last slidein all copies of the document to comply with the attribution
requirements of the license. If you make a change, feel free toadd your name and organization to the list of contributors on thispage as you republish the materials.
Initial Development: Charles Severance, University of MichiganSchool of Information
… Insert new Contributors and Translators here
...
http://open.umich.edu/http://www.dr-chuck.com/http://www.dr-chuck.com/