Class 20 – October 9
You are so controlling
While I can go on – I do not repeat myself – Always a new way
Look both ways
Agenda
- Introduce the
while
statement and foreshadowdict
Problems
- Program spell_check.py
- Program yes_or_no.py
- Program guess_what.py
- Program even_odd.py
- Program que_dijiste.py
Whiling away
- Like many programming languages, Python provides more than one way to iterate actions (repeatedly execute). We are concerned here with its
while
looping offering.
- The
while
loop differs from thefor
loop in that the number of times it iterates is not based on the size of a list or range; instead, iteration is based on a logical test expression.
- The basic
while
state has the form:
while ( test expression ) :
action
- When Python reaches a
while
loop, it will repeatedly execute the loop's actions as long as the test expression evaluates to true. When the test expression evaluates false, the program drops down to the statement following the loop. Example:
looking_for_a_yes_or_no = True
while ( looking_for_a_yes_or_no ) :
reply = input( 'Enter (yes / no): ' )
reply = reply.lower()
if ( reply in [ 'yes', 'no' ]
looking_for_a_yes_or_no = False
- The
while
statement also allows an optionalelse
.
while ( test expression ) :
action
else :
action
- The
else
action is executed once the test expression evaluates to false. Example usage is below.
looking_for_a_yes_or_no = True
while ( looking_for_a_yes_or_no ) :
reply = input( 'Enter (yes / no): ' )
reply = reply.lower()
if ( reply in [ 'yes', 'no' ]
looking_for_a_yes_or_no = False
else :
print( 'your reply of', reply, 'is accepted' )
Note, I have never needed to use
else
for awhile
statement in practice.