Block F

Indefinite Looping with while

picture of Stephen Colbert

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.


from random import shuffle
def is_in_order(x):
    """prec: x is a homogeneous list of sortable items
    post: returns true if the list is in ascending order."""
    k = 0
    while k < len(x) -1:
        if x[k] > x[k+1]:
            return False
        k += 1
    return True
def bozo(x):
    while not is_in_order(x):
        shuffle(x)

x = [3,-2, 5, 7, 9, -10, 6, 1, 2]
bozo(x)
print(x)
##Challenge: cna you write a a for loop version of is_in_order?
def is_in_order_for(x):
    pass

def is_in_order(x):
    """prec: x is a homogeneous list of sortable items
    postc: returns True if the list is in ascending order"""
    for k in range(len(x)-1):
        if x[k] > x[k+1]:
            return False
    return True

def is_in_order_for(x):
    """prec: x is a homogeneous list of sortable items
    postc: returns True if the list is in ascending order"""
    for k in range(len(x)-1):
        if x[k] > x[k+1]:
            return False
    return True

Let's write the Bozo Sort! Here is the algorithm

  1. Check to see if the list is sorted in order
  2. If it is, you are done.
  3. 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.


from random import randint
secret_number = randint(1,100)
guess = 0
while secret_number != guess:
    guess = input("Enter a guess:   ")
    guess = int(guess)
    if secret_number >  guess:
        print(f"Your guess {guess} is too low.")
    elif secret_number <  guess:
        print(f"Your guess {guess} is too high.")
print(f"Your guess, {guess}, is correct!")

Can you tell the user how many guesses he made?

Haugan


from random import randint
secret_number = randint(1,100)
guess = 0
count = 0
while secret_number != guess:
    guess = int(input("Enter a guess:  "))
    if secret_number > guess:
        print(f" Your guess {guess} is too low.")
        count+=1
    elif secret_number < guess:
        print(f" Your guess {guess} is too high.")
        count+=1

print(f"Your guess,{guess}, is correct! and you guessed {count} times!")

from random import randint
secret_number = randint(1,100)
guess = 0
count = 0
while secret_number != guess:
    guess = int(input("Enter a guess:  "))
    if secret_number > guess:
        print(f" Your guess {guess} is too low.")
        count+=1
    elif secret_number < guess:
        print(f" Your guess {guess} is too high.")
        count+=1

print(f"Your guess,{guess}, is correct! and you guessed {count} times!")

from random import randint
secret_number = randint(1,100)
guess = 0
count = 0
while secret_number != guess:
    guess = int(input("Enter a guess:  "))
    if secret_number > guess:
        print(f" Your guess {guess} is too low.")
        count+=1
    elif secret_number < guess:
        print(f" Your guess {guess} is too high.")
        count+=1

print(f"Your guess,{guess}, is correct! and you guessed {count} times!")

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.


def is_integer_string(x):
    k = 0
    if x[k] in "+-":
        k += 1
    while k < len(x):
        if not x[k].isdigit():
            return False
        k += 1
    return True
entry = "cows"
while not is_integer_string(entry):
    entry = input("Enter an integer:  ")

Mini Case Study: Roll a fair pair of dice until you get doubles Print out the rolls


from random import randint
a,b,i=0,7,0
while a!=b:
    i+=1
    a,b=randint(1,6),randint(1,6)
    print(f"Roll {i}: Rolled a {a} and a {b}")

from random import randint

def roll_dice():
    return (randint(1,6), randint(1,6))
x, y = 0, 1
rolls = 0
while x != y:
    rolls += 1
    x, y = roll_dice()
    print(x,y)
print(f"Got a double! Took {rolls} rolls!")

Mini Case Study: Flip a fair coin until N heads occur N is a command line argument.

Haugan


from sys import argv
from random import randint
h, s = 0, ""
while h<int(argv[1]):
    c=randint(0,1)
    h,s = h + c,s + ["T","H"][c]
print(f"Achieved {h} Heads after {len(s)} Flips: {s}")

from random import choice
from sys import argv
N = int(argv[1])
flips = 0
heads = 0
results = ""
coin = ["H", "T"]
while heads < N:
    flips +=1
    res = choice(coin)
    if res == "H":
        heads += 1
    results += res
print(results)
print(f"Got {N} heads after {flips} flips.")

Fujita


from sys import argv
from random import randint
N = int(argv[1])
count = 0
string = ""
Heads = 0
while Heads < N:
    tosses = randint(0,1)
    if tosses == 0:
        string += "H"
        Heads +=1
    elif tosses == 1:
        string += "T"
    count+=1

print(f"You tossed {count} times to get {Heads} heads and your result were {string}")

Can you change each for to a while? Get your name in lights by pasting a solution into chat!


def print_list(x):
    for k in x:
        print(k)
x = ["a", 1, True]
print_list(x)

def print_list(x):
    k = 0
    while k < len(x):
        print(x[k])
        k+=1
x = ["a", 1, True]
print_list(x)

def count_down(n):
    for k in reversed(range(n + 1)):
        print k
    print("Blastoff!")
count_down(10)

def count_down_while(n):
    while n > =0:
        print(n)
        n-=1

Gamboa


def count_down(n):
    while n > 0:
        print(n)
        n-=1
    print("Blastoff!")
count_down(10)

def harvest_caps(s):
    out = ""
    for k in s:
        if k.isupper():
            out += k
    return out
print(harvest_caps("AEioU"))