Conditional Functions Iterations
Conditional Functions Iterations
Function
Loops and Iteration
x=5
Conditional Steps
Yes
x < 10 ?
No print('Smaller') Program:
Output:
x = 5
Yes if x < 10: Smaller
x > 20 ? print('Smaller') Finis
if x > 20:
No print('Bigger') print('Bigger')
print('Finis')
print('Finis')
Comparison Operators
• Boolean expressions ask a Python Meaning
question and produce a Yes or No < Less than
result which we use to control
program flow <= Less than or Equal to
== Equal to
• Boolean expressions using >= Greater than or Equal to
comparison operators evaluate to
> Greater than
True / False or Yes / No
!= Not equal
• Comparison operators look at
variables but do not change the Remember: “=” is used for assignment.
variables
http://en.wikipedia.org/wiki/George_Boole
Comparison Operators
x = 5
if x == 5 :
print('Equals 5') Equals 5
if x > 4 :
print('Greater than 4')
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 :
print('Less than or Equals 5') Less than or Equals 5
if x != 6 :
print('Not equal 6') Not equal 6
One-Way Decisions
x = 5 Yes
print('Before 5') Before 5 x == 5 ?
if x == 5 :
print('Is 5') Is 5 print('Is 5’)
No
print('Is Still 5')
Is Still 5
print('Third 5')
print('Afterwards 5')
Third 5 print('Still 5')
print('Before 6') Afterwards 5
if x == 6 : Before 6 print('Third 5')
print('Is 6')
print('Is Still 6')
print('Third 6')
print('Afterwards 6') Afterwards 6
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)
• 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
This will save you
much unnecessary
pain.
increase / maintain after if or for
decrease to indicate end of block
x = 5
if 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', i)
print('All Done')
Think About begin/end Blocks
x = 5
if 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', i)
print('All Done')
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')
print('All Done')
Two-way Decisions
x=4
• Sometimes we want to
do one thing if a logical no yes
x>2
expression is true and
something else if the
expression is false print('Not bigger') print('Bigger')
if x > 2 :
print('Bigger') print('Not bigger') print('Bigger')
else :
print('Smaller')
print('All done')
print('All Done')
Visualize Blocks x=4
no yes
x = 4 x>2
if x > 2 :
print('Bigger') print('Not bigger') print('Bigger')
else :
print('Smaller')
print('All done')
print('All Done')
More Conditional Structures…
Multi-way
yes
x<2 print('small')
no
if x < 2 :
yes
print('small')
elif x < 10 :
x < 10 print('Medium')
print('Medium') no
else :
print('LARGE') print('LARGE')
print('All done')
print('All Done')
x=0
Multi-way
yes
x<2 print('small')
x = 0
no
if x < 2 :
yes
print('small')
elif x < 10 :
x < 10 print('Medium')
print('Medium') no
else :
print('LARGE') print('LARGE')
print('All done')
print('All Done')
x=5
Multi-way
yes
x<2 print('small')
x = 5
no
if x < 2 :
yes
print('small')
elif x < 10 :
x < 10 print('Medium')
print('Medium') no
else :
print('LARGE') print('LARGE')
print('All done')
print('All Done')
x = 20
Multi-way
yes
x<2 print('small')
x = 20
no
if x < 2 :
yes
print('small')
elif x < 10 :
x < 10 print('Medium')
print('Medium') no
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
regardless of the value for x?
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
Output Main
Devices Memory
Generic
Software
Computer
Input
Central
Devices
Processing
Unit
Secondary
Memory
Output Main
Devices Memory
astr = 'Hello Bob' When the first conversion fails - it
try: just drops into the except: clause
istr = int(astr) and the program continues.
except:
istr = -1
$ python tryexcept.py
print('First', istr) First -1
Second 123
astr = '123'
try:
istr = int(astr)
except:
istr = -1 When the second conversion
succeeds - it just skips the except:
print('Second', istr) clause and the program continues.
astr = 'Bob'
try / except
print('Hello')
astr = 'Bob'
try:
print('Hello') istr = int(astr)
istr = int(astr)
print('There')
except: print('There')
istr = -1
istr = -1
print('Done', istr)
Enter Hours: 45
Enter Rate: 10
Pay: 475.0
475 = 40 * 10 + 5 * 15
Exercise
Enter Hours: 20
Enter Rate: nine
Error, please enter numeric input
Result
>>> big = max('Hello world')
>>> print(big)
w
>>> tiny = min('Hello world')
>>> print(tiny)
>>>
Max Function
A function is some
>>> big = max('Hello world') stored code that we
>>> print(big)
use. A function takes
w
some input and
produces an output.
• This defines the function but does not execute the body of the
function
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print('I sleep all night and I work all day.')
print("I'm a lumberjack, and I'm okay.")
print_lyrics(): print('I sleep all night and I work all day.')
x = 5
print('Hello')
def print_lyrics():
print("I'm a lumberjack, and I'm okay.") Hello
print('I sleep all night and I work all day.')
Yo
print('Yo') 7
x = x + 2
print(x)
Definitions and Uses
• Once we have defined a function, we can call (or invoke) it
as many times as we like
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print('I sleep all night and I work all day.')
print('Yo')
print_lyrics()
x = x + 2
Hello
print(x) Yo
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
7
Arguments
• An argument is a value we pass into the function as its input
when we call the function
def greet():
return "Hello" Hello Glenn
Hello Sally
print(greet(), "Glenn")
print(greet(), "Sally")
Return Value
>>> def greet(lang):
... if lang == 'es':
• A “fruitful” function is one ... return 'Hola'
... elif lang == 'fr':
that produces a result (or ... return 'Bonjour'
return value) ... else:
... return 'Hello'
...
• The return statement ends >>> print(greet('en'),'Glenn')
the function execution and Hello Glenn
>>> print(greet('es'),'Sally')
“sends back” the result of Hola Sally
the function >>> print(greet('fr'),'Michael')
Bonjour Michael
>>>
Arguments, Parameters, and
Results
>>> big = max('Hello world') Parameter
>>> print(big)
w
def max(inp):
blah
blah
'Hello world' for x in inp: 'w'
blah
blah
Argument return 'w'
Result
Multiple Parameters / Arguments
• We can define more than one
parameter in the function def addtwo(a, b):
definition added = a + b
return added
• We simply add more arguments
x = addtwo(3, 5)
when we call the function print(x)
Enter Hours: 45
Enter Rate: 10
Pay: 475.0
475 = 40 * 10 + 5 * 15
n=5 Repeated Steps
Output:
No Yes Program:
n>0? 5
n = 5 4
print(n) while n > 0 :
3
print(n)
n = n – 1 2
n = n -1 print('Blastoff!') 1
print(n) Blastoff!
0
Loops (repeated steps) have iteration variables that
print('Blastoff') change each time through a loop. Often these iteration
variables go through a sequence of numbers.
n=5 An Infinite Loop
No Yes
n>0?
n = 5
while n > 0 :
print('Lather')
print('Lather')
print('Rinse')
print('Rinse') print('Dry off!')
• It is like a loop test that can happen anywhere in the body of the
loop
while True: > hello there
line = input('> ') hello there
if line == 'done' : > finished
break finished
print(line) > done
print('Done!') Done!
Breaking Out of a Loop
• The break statement ends the current loop and jumps to the
statement immediately following the loop
• It is like a loop test that can happen anywhere in the body of the
loop
while True: > hello there
line = input('> ') hello there
if line == 'done' : > finished
break finished
print(line) > done
print('Done!') Done!
No Yes
while True: True ?
line = input('> ')
if line == 'done' :
....
break
print(line)
print('Done!')
break
...
print('Done')
Finishing an Iteration with
continue
The continue statement ends the current iteration and jumps to the
top of the loop and starts the next iteration
while True:
> hello there
line = input('> ')
if line[0] == '#' : hello there
continue > # don't print this
if line == 'done' : > print this!
break print this!
print(line) > done
print('Done!') Done!
Finishing an Iteration with
continue
The continue statement ends the current iteration and jumps to the
top of the loop and starts the next iteration
while True:
> hello there
line = input('> ')
if line[0] == '#' : hello there
continue > # don't print this
if line == 'done' : > print this!
break print this!
print(line) > done
print('Done!') Done!
No
True ? Yes
while True:
line = raw_input('> ') ....
if line[0] == '#' :
continue
if line == 'done' : continue
break
print(line)
...
print('Done!')
print('Done')
Indefinite Loops
• While loops are called “indefinite loops” because they keep
going until a logical condition becomes False
• The loops we have seen so far are pretty easy to examine to see
if they will terminate or if they will be “infinite loops”
• We can write a loop to run the loop once for each of the items in
a set using the Python for construct
i=2
3
What is the Largest Number?
41
What is the Largest Number?
12
What is the Largest Number?
9
What is the Largest Number?
74
What is the Largest Number?
15
What is the Largest Number?
What is the Largest Number?
3 41 12 9 74 15
What is the Largest Number?
largest_so_far -1
What is the Largest Number?
largest_so_far 3
What is the Largest Number?
41
largest_so_far 41
What is the Largest Number?
12
largest_so_far 41
What is the Largest Number?
largest_so_far 41
What is the Largest Number?
74
largest_so_far 74
What is the Largest Number?
15
74
What is the Largest Number?
3 41 12 9 74 15
74
Finding the Largest Value
$ python largest.py
largest_so_far = -1
Before -1
print('Before', largest_so_far)
for the_num in [9, 41, 12, 3, 74, 15] : 9 9
if the_num > largest_so_far : 41 41
largest_so_far = the_num 41 12
print(largest_so_far, the_num) 41 3
74 74
print('After', largest_so_far) 74 15
After 74
We make a variable that contains the largest value we have seen so far. If the current
number we are looking at is larger, it is the new largest value we have seen so far.
More Loop Patterns…
Counting in a Loop
$ python countloop.py
zork = 0 Before 0
print('Before', zork) 19
for thing in [9, 41, 12, 3, 74, 15] :
2 41
zork = zork + 1
print(zork, thing) 3 12
print('After', zork) 43
5 74
6 15
After 6
If we just want to search and know if a value was found, we use a variable that
starts at False and is set to True as soon as we find what we are looking for.
How to Find the Smallest Value
$ python largest.py
largest_so_far = -1
Before -1
print('Before', largest_so_far)
for the_num in [9, 41, 12, 3, 74, 15] : 9 9
if the_num > largest_so_far : 41 41
largest_so_far = the_num 41 12
print(largest_so_far, the_num) 41 3
74 74
print('After', largest_so_far) 74 15
After 74
How would we change this to make it find the smallest value in the list?
Finding the Smallest Value
smallest_so_far = -1
print('Before', smallest_so_far)
for the_num in [9, 41, 12, 3, 74, 15] :
if the_num < smallest_so_far :
smallest_so_far = the_num
print(smallest_so_far, the_num)
print('After', smallest_so_far)
We switched the variable name to smallest_so_far and switched the > to <
Finding the Smallest Value
$ python smallbad.py
smallest_so_far = -1
Before -1
print('Before', smallest_so_far)
for the_num in [9, 41, 12, 3, 74, 15] : -1 9
if the_num < smallest_so_far : -1 41
smallest_so_far = the_num -1 12
print(smallest_so_far, the_num) -1 3
-1 74
print('After', smallest_so_far) -1 15
After -1
We switched the variable name to smallest_so_far and switched the > to <
Finding the Smallest Value
smallest = None $ python smallest.py
print('Before') Before
for value in [9, 41, 12, 3, 74, 15] : 99
if smallest is None :
9 41
smallest = value
elif value < smallest : 9 12
smallest = value 33
print(smallest, value) 3 74
print('After', smallest) 3 15
After 3
We still have a variable that is the smallest so far. The first time through the loop
smallest is None, so we take the first value to be the smallest.
The is and is not Operators
• Python has an is operator
smallest = None that can be used in logical
print('Before') expressions
for value in [3, 41, 12, 9, 74, 15] :
if smallest is None :
• Implies “is the same as”
smallest = value
elif value < smallest :
smallest = value • Similar to, but stronger than
print(smallest, value) ==
print('After', smallest)
• is not also is a logical
operator
Summary
• While loops (indefinite) • For loops (definite)
• Infinite loops • Iteration variables
• Using break • Loop idioms
• Using continue • Largest or smallest
• None constants and variables