Block B

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   ##omit this an you will have spewing!

We can also exploit the falsiness of 0 as seen here.


print("Blastoff!")    
n = 10
while n:        # when n is 0, predicate is falsy
    print(n)
    n -= 1   
print("Blastoff!")    

Here we exploit the falsiness of an empty string.


s = "abcdef"
while s:
    print(s)
    s = s[1:]

Nagging This can be used to ask for user input until some desired condition is achieved.


import random
secret = random.randint(1,100)
guess = int(input("Enter a guess, 1-100:  "))
while guess != secret:
    if guess < secret:
        print("Your guess is too low.")
    elif guess > secret:
        print("Your guess is too high.")
    print("Try again!")
    guess = int(input("Enter a guess, 1-100:  "))
print(f"You guessed the secret number {secret}!")

Stochastic Simulation: A Coin Experiment

First we toss a fair coin. Run this a bunch of times to check it out.


import random
def toss():
    return random.choice("HT")
for k in range(40):
    print(toss(), end=" ")
print("")

Now we are going to count the number of tosses until a head occurs and return that number.


import random
NUMBER_OF_TRIALS = 1000000
def toss():
    return random.choice("HT")
def do_trial():
    chocula = 1
    while toss() != "H":
        chocula += 1
    return chocula
## run it to check it out.
for k in range(40):
    print(toss(), end=" ")
print("")

Now we are going to conduct this experiment and create a tally of reslts.


import random
NUMBER_OF_TRIALS = 1000000
def toss():
    return random.choice("HT")
def do_trial():
    chocula = 1
    while toss() != "H":
        chocula += 1
    return chocula
def do_big_experiment():
    tally = {}
    for k in range(NUMBER_OF_TRIALS):
        trial = do_trial()             #run the trial
        if trial not in tally:         #if the result hasn't been seen
            tally[trial] = 1           #enroll it in the dictionary with value 1.
        else:
            tally[trial] += 1          #if the result has been seen
    return tally                       #increment its value.

d = do_big_experiment()
sorted_keys = sorted(d.keys())         #sort the keys
for key in sorted_keys:
    print(f"{key}\t\t{d[key]}")        #print the tally
total = 0
for key in d:                          #find the average
    total += key*d[key]
print(f"average is {total/NUMBER_OF_TRIALS}")