2 Python2 Conditionals
2 Python2 Conditionals
1-2
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
Different types of decisions
• Nested Decisions
• Chained Conditionals
1-3
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
Recall: one way decision
Decision Structures in Pseudo code and flowchart
The if statement
– An action only occurs if the decision is true
If condition Then
Statement
Statement
End If
– A diamond symbol is used in flowcharts
1-4
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
IF-statement Syntax in python
Pseudocode Python
if expression:
statement(s)
Note the indent
Program:
x=5
Yes if x < 10:
print 'Smaller‘
if x > 20:
print 'Bigger'
print 'Finish'
Excercise x=5
if x < 10:
print ('Smaller')
if x >= 5 :
print ('Greater than or Equal 5')
if x < 6 :
print ('Less than 6')
IF with multiple
Yes
Statement
x=5 No
if x == 5 :
print 'Is 5‘
print 'Is Still 5'
print 'Third 5’
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)
if x > 2 :
print 'Bigger'
else :
print 'Smaller'
Write a python script that prompts for and input a student course
grade. Use if-else statements to determine if the student pass or
fail in the course. (passing grade is >=60).
yes
Nested
Decisions no
x = 42
yes
if x > 1 :
print 'More than one'
no
if x < 100 :
print 'Less than 100'
if x < 2 :
no
print 'Small'
elif x < 10 : yes
print 'Medium' no
else :
print 'LARGE'
print 'All done'
Exercise
In general, catching an exception gives you a chance to fix the problem, or try again, or at least end the
program gracefully.
astr = 'Hello Bob‘ $ python notry.py Traceback (most
istr = int(astr) recent call last): File "notry.py", line 2,
print 'First‘ in <module> istr =
istrastr = '123‘ int(astr)ValueError: invalid literal for
istr = int(astr) int() with base 10: 'Hello Bob'
print 'Second', istr
astr = 'Hello Bob'
try: When the first conversion fails - it
just drops into the except: clause and
istr = int(astr) the program continues.
except:
istr = -1
Output:
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.
try:
ival = int(rawstr)
Enter a number:42
except:
Nice work
ival = -1
Enter a number:fourtytwo
if ival > 0 :
Not a number
print 'Nice work’
else:
print 'Not a number’
Exercise
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