3.1 Conditional Statements
3.1 Conditional Statements
PYTHON FOR
EVERYBODY
Conditional Execution
Chapter 3
x=5
Conditional Steps
Yes
x < 10 ? Program Output
print('Smaller')
x = 5
if x < 10: Smaller
print('Smaller')
x > 20 ? if x > 20:
No
print('Bigger')
print('Bigger')
print('Finis') Finis
print('Finis')
Conditional – Part 1
PYTHON FOR
EVERYBODY
Comparison Operators
• Boolean expressions ask a question
and produce a Yes or No result which Python Meaning
we use to control program flow < Less than
<= Less than or Equal to
• Boolean expressions using
== Equal to
comparison operators evaluate to
True / False or Yes / No >= Greater than or Equal to
> Greater than
• Comparison operators look at != Not equal
variables but do not change the
variables
Remember: “=” is used for assignment.
http://en.wikipedia.org/wiki/George_Boole
Conditional – Part 1
PYTHON FOR
EVERYBODY
Comparison Operators
x = 5
if x == 5 :
Equals 5
print('Equals 5')
if x > 4 :
Greater than 4
print('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 :
Less than or Equals 5
print('Less than or Equals 5')
if x != 6 :
Not equal 6
print('Not equal 6')
Conditional – Part 1
PYTHON FOR
EVERYBODY
One-Way Decisions
x = 5 Yes
print('Before 5') x == 5 ?
if x == 5 : Before 5
print('Is 5') Is 5
No print('Is 5’)
print('Is Still 5') Is Still 5
print('Third 5') Third 5
print('Afterwards 5') print('Still 5')
Afterwards 5
print('Before 6')
Before 6
if x == 6 : print('Third 5')
print('Is 6')
Afterwards 6
print('Is Still 6')
print('Third 6')
print('Afterwards 6')
Conditional – Part 1
PYTHON FOR
EVERYBODY
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)
Atom automatically uses spaces for files with ".py" extension (nice!)
• Most text editors can turn tabs into spaces - make sure to enable this feature
• 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
Conditional – Part 1
PYTHON FOR
EVERYBODY
for i in range(5) :
print(i)
if i > 2 :
print('Bigger than 2')
print('Done with i', i)
print('All Done')
Conditional – Part 1
PYTHON FOR
EVERYBODY
for i in range(5) :
print(i)
if i > 2 :
print('Bigger than 2')
print('Done with i', i)
print('All Done')
Conditional – Part 1
PYTHON FOR
EVERYBODY
Nested x>1
yes
x = 42
if x > 1 : yes
print('More than one') x < 100
if x < 100 :
no
print('Less than 100') print('Less than 100')
print('All done')
with else:
no yes
x = 4 x>2
if x > 2 :
print('Not bigger') print('Bigger')
print('Bigger')
else :
print('Smaller')