Indefinite Looping with while
Truthiness and Falsiness A value is truthy if
when it is cast to a boolean, it casts to True
. A value is
Falsy if when it is cast to a boolean, it casts to False
.
Note that if
statements will act on truthiness and falsiness.
Afraid of commitment? So far, our looping has been walking through a collection such as a list, dictionary, or range object. Now we will look at a construct that can loop indefinitely.
Interchangeability The while
loop is all you
really need. However as you will see, the for
loop is less
error-prone.
A while
statement is a boss statement. It looks like this.
while predicate:
block
The predicate is something that is truthy or falsy. If the predicate is truthy, the block runs. If not, you are out of the loop. Think of this as a "sticky if."
Let's write a function to see if a numerical list is in order.
def is_in_order(x):
"""prec: x is a homogeneous list of sortable items
postc: returns True if the list is in ascending order"""
pass
def is_in_order_for(x):
pass
Let's write the Bozo Sort! Here is the algorithm
- Check to see if the list is sorted in order
- If it is, you are done.
- If not, shuffle and repeat.
def bozo(x):
pass
x = [5,2,8,9, 3]
bozo(x)
print(x)
Can you change each for
to a while
?
Get your name in lights by pasting a solution into chat!
def print_list(x):
pass
Hanging and Spewing Uh oh,
while
gone wild. Hanging is when your
program stops for "no good reason." It's frozen.
Spewing occurs when your program spews text to the screen withut surcease. In this case use control-c(Unix) or control-z(windoze).
Mini Case Study: A Number Guessing Game The computer picks a random integer 1-100 and it tells you if your guess is too high, too low, or if it is correct.
Can you tell the user how many guesses he made?
Mini Case Study: Nagging a Dolt This program asks a user to enter an integer. It nags the user until a parseable integer is entered.
Mini Case Study: Roll a fair pair of dice until you get doubles Print out the rolls
Mini Case Study: Flip a fair coin until N heads occur N is a command line argument.