Block F

while

Indefinite looping

This is Python's indefinite loop. Its general form is


while predicate:
    block

You can think of while as a "sticky if," which keeps executing until the predicate is falsy.


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

Here in these examples we use falsiness. The integer 0 is falsy, as is an empty sequence [in this case, a string].


n = 10
while n:
    print(n)
    n -= 1
print("Blastoff!")
x = [1,2,3,4,5,6]
while x:
    print(x)
    x = x[1:]

Nagging This is an application of the principle "until is while not." Until a correct guess is given, the program continues to request further guesses.


import random
secret = random.randint(1,100)
guess = -1
while guess != secret:
    guess = int(input("Guess an integer 1-100:"))
    if guess > secret:
        print("Your guess is too big.")
    elif guess < secret:
        print("Your guess is too small")
print(f"You have guess the secret number {guess} correctly!")

Stochastic Simulation: A Coin Experiment

We are interested in the number of tosses it takes for a head to appear when flipping a fair coin. We will perform this experiment 1,000,000 times.

We being by creating a coin toss function.


import random
def toss():
    return random.choice("HT")

You can run this with a loop and see it generate tosses. Next, we do a single trial of the experiment. Note the use of "while not" as until.


import random
def toss():
    return random.choice("HT")
def do_trial():
    chocula = 1
    while toss() != "H":      #  until is "while not"
        chocula += 1
    return chocula

You can run this repeatedly as a loop. Next what we need to do is to tally the results. This tally will be housed in a dictionary, since the (integer) results are hashable. The keys will be the results, and the values the number of times each result is observed.

For each observation, we do one of two things.


import random
def toss():
    return random.choice("HT")
def do_trial():
    chocula = 1
    while toss() != "H":      #  until is "while not"
        chocula += 1
    return chocula
def run_experiment(num_times):
    out = {}
    for k in range(num_times):
        result = do_trial()
        if result in out:
            out[result] += 1
        else:
            out[result] = 1
    return out
d = run_experiment(1000000)
sorted_keys = sorted(d.keys())
for k in sorted_keys:
    print(f"{k}\t\t{d[k]}")