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

Pythonlearn 03 Conditional

The document discusses conditional execution in Python programs. It provides an example Python program that uses conditional statements like if/else to check if a variable x is less than 10, greater than 20, and print corresponding output. The summary is: 1) The document discusses conditional execution and control flow in Python using comparison operators like <, >, == in conditional statements. 2) It provides a sample Python program that uses if/else statements to check if a variable x is less than 10, greater than 20, and print output accordingly. 3) The program outputs "Smaller" since x=5 is less than 10, demonstrating conditional execution in Python.

Uploaded by

Hưng Minh Phan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Pythonlearn 03 Conditional

The document discusses conditional execution in Python programs. It provides an example Python program that uses conditional statements like if/else to check if a variable x is less than 10, greater than 20, and print corresponding output. The summary is: 1) The document discusses conditional execution and control flow in Python using comparison operators like <, >, == in conditional statements. 2) It provides a sample Python program that uses if/else statements to check if a variable x is less than 10, greater than 20, and print output accordingly. 3) The program outputs "Smaller" since x=5 is less than 10, demonstrating conditional execution in Python.

Uploaded by

Hưng Minh Phan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

10/01/21

x=5
Conditional Steps
Yes
x < 10 ?

Program:
Conditional Execution No print('Smaller') Output:
x = 5
Smaller
Chapter 3 x > 20 ?
Yes if x < 10:
print('Smaller') Finis
if x > 20:
No print('Bigger')
print('Bigger')
print('Finis')
Python for Everybody
www.py4e.com print('Finis')

1 2

Comparison Operators Comparison Operators


• Boolean expressions ask a Python Meaning x = 5
question and produce a Yes or No < Less than if x == 5 :
result which we use to control print('Equals 5') Equals 5
program flow <= Less than or Equal to
if x > 4 :
== Equal to print('Greater than 4') Greater than 4
• Boolean expressions using >= Greater than or Equal to if x >= 5 :
comparison operators evaluate to Greater than or Equals 5
> Greater than print('Greater than or Equals 5')
True / False or Yes / No
!= Not equal if x < 6 : print('Less than 6') Less than 6
if x <= 5 :
• Comparison operators look at
variables but do not change the
print('Less than or Equals 5') Less than or Equals 5
Remember: “=” is used for assignment. if x != 6 :
variables
http://en.wikipedia.org/wiki/George_Boole print('Not equal 6') Not equal 6

3 4
10/01/21

One-Way Decisions
x = 5 Yes Indentation
print('Before 5') Before 5 x == 5 ?
if x == 5 :
• Increase indent indent after an if statement or for statement (after : )
print('Is 5') Is 5 No print('Is 5’)
print('Is Still 5')
Is Still 5 • Maintain indent to indicate the scope of the block (which lines are affected
print('Third 5')
Third 5 print('Still 5') by the if/for)
print('Afterwards 5')
print('Before 6') Afterwards 5
• Reduce indent back to the level of the if statement or for statement to
if x == 6 : Before 6 print('Third 5') indicate the end of the block
print('Is 6')
print('Is Still 6') • Blank lines are ignored - they do not affect indentation
print('Third 6')
print('Afterwards 6') Afterwards 6 • Comments on a line by themselves are ignored with regard to indentation

5 6

This will save you


Warning: Turn Off Tabs!! much unnecessary
pain.
• Atom automatically uses spaces for files with ".py" extension (nice!)

• 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 a line is indented. If you mix tabs and
spaces, you may get “indentation errors” even if everything looks fine

7 8
10/01/21

increase / maintain after if or for Think About begin/end Blocks


decrease to indicate end of block
x = 5 x = 5
if x > 2 : if x > 2 :
print('Bigger than 2') print('Bigger than 2')
print('Still bigger') print('Still bigger')
print('Done with 2') print('Done with 2')

for i in range(5) : for i in range(5) :


print(i) print(i)
if i > 2 : if i > 2 :
print('Bigger than 2') print('Bigger than 2')
print('Done with i', i) print('Done with i', i)
print('All Done') print('All Done')

9 10

Nested x>1
yes
Two-way Decisions
Decisions no
x=4
print('More than one’) • Sometimes we want to
x = 42 do one thing if a logical no yes
x>2
if x > 1 : yes expression is true and
x < 100
print('More than one') something else if the
if x < 100 : expression is false print('Not bigger') print('Bigger')
no
print('Less than 100') print('Less than 100')
print('All done')
• It is like a fork in the
road - we must choose
one or the other path but print('All Done')
print('All Done')
not both

11 12
10/01/21

Two-way Decisions Visualize Blocks


x=4 x=4
with else:
no yes no yes
x = 4 x>2 x = 4 x>2

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

print('All done') print('All done')


print('All Done') print('All Done')

13 14

Multi-way
yes
x<2 print('small')

More Conditional Structures… if x < 2 :


print('small')
no
yes
elif x < 10 :
x < 10 print('Medium')
print('Medium') no
else :
print('LARGE') print('LARGE')
print('All done')

print('All Done')

15 16
10/01/21

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

print('All Done') print('All Done')

17 18

x = 20
Multi-way Multi-way if x < 2 :
yes print('Small')
x<2 print('small') elif x < 10 :
x = 20 # No Else print('Medium')
no elif x < 20 :
if x < 2 : x = 5
yes print('Big')
print('small') if x < 2 :
x < 10 print('Medium') elif x < 40 :
elif x < 10 : print('Small')
print('Medium') no elif x < 10 : print('Large')
else : print('Medium') elif x < 100:
print('LARGE') print('LARGE') print('Huge')
print('All done') print('All done') else :
print('Ginormous')
print('All Done')

19 20
10/01/21

Multi-way Puzzles The try / except Structure


Which will never print
regardless of the value for x?
if x < 2 : • You surround a dangerous section of code with try and except
• If the code in the try works - the except is skipped
print('Below 2')
if x < 2 : elif x < 20 :
print('Below 2') print('Below 20')
elif x >= 2 : elif x < 10 : • If the code in the try fails - it jumps to the except section
print('Two or more') print('Below 10')
else : else :
print('Something else') print('Something else')

21 22

$ python3 notry.py $ python3 notry.py


Traceback (most recent call last): Traceback (most recent call last):
File "notry.py", line 2, in <module> File "notry.py", line 2, in <module>
istr = int(astr)ValueError: invalid literal The istr = int(astr)ValueError: invalid literal
for int() with base 10: 'Hello Bob' program for int() with base 10: 'Hello Bob'
$ cat notry.py stops $ cat notry.py
astr = 'Hello Bob' All here astr = 'Hello Bob' All
istr = int(astr) Done istr = int(astr) Done
print('First', istr) print('First', istr)
astr = '123' astr = '123'
istr = int(astr) istr = int(astr)
print('Second', istr) print('Second', istr)

23 24
10/01/21

Generic Generic
Software Software
Computer Computer
Input Input
Central Central
Devices Devices
Processing Processing
Unit Unit
Secondary Secondary
Memory Memory

Output Main Output Main


Devices Memory Devices Memory

25 26

astr = 'Hello Bob'


try:
When the first conversion fails - it
just drops into the except: clause
and the program continues.
try / except astr = 'Bob'

istr = int(astr)
except: print('Hello')
istr = -1 astr = 'Bob'
$ python tryexcept.py try:
print('First', istr) First -1 print('Hello') istr = int(astr)
Second 123 istr = int(astr)
astr = '123' print('There')
try: except: print('There')
istr = int(astr) istr = -1
except:
istr = -1
istr = -1 When the second conversion print('Done', istr)
succeeds - it just skips the except: Safety net
print('Second', istr) clause and the program continues. print('Done', istr)

27 28
10/01/21

Sample try / except Summary


rawstr = input('Enter a number:') • Comparison operators • Nested Decisions
try: == <= >= > < !=
ival = int(rawstr) $ python3 trynum.py • Multi-way decisions using elif
except: Enter a number:42 • Indentation
ival = -1 Nice work • try / except to compensate for
$ python3 trynum.py • One-way Decisions errors
if ival > 0 : Enter a number:forty-two
print('Nice work') Not a number • Two-way decisions:
else: $ if: and else:
print('Not a number')

29 30

Exercise Exercise

Rewrite your pay program using try and except so


Rewrite your pay computation to give the that your program handles non-numeric input
employee 1.5 times the hourly rate for hours gracefully.
worked above 40 hours.
Enter Hours: 20
Enter Hours: 45 Enter Rate: nine
Enter Rate: 10 Error, please enter numeric input
Pay: 475.0 Enter Hours: forty
475 = 40 * 10 + 5 * 15
Error, please enter numeric input

31 32
10/01/21

Acknowledgements / Contributions
These slides are Copyright 2010- Charles R. Severance
(www.dr-chuck.com) of the University of Michigan School of ...
Information and made available under a Creative Commons
Attribution 4.0 License. Please maintain this last slide in all
copies of the document to comply with the attribution
requirements of the license. If you make a change, feel free to
add your name and organization to the list of contributors on this
page as you republish the materials.

Initial Development: Charles Severance, University of Michigan


School of Information

… Insert new Contributors and Translators here

33

You might also like