Lecture Notes on 05 Mar 2014 There are two different ways of using while - with a counter and with a sentinel value. Paradigm 1: Counter * Initialize counter outside the loop * Create a boolean conditional expression with the counter to terminate the loop * Reset (increment or decrement) the counter in the body of the loop Paradigm 2: Sentinel Value * Read input or initialize variable that may have the sentinel value * Create boolean conditional expression with sentinel value * Read input within the body of the loop or reset the variable that may have the sentinel value Outline of Assignment 6 def main(): # Prompt the user to enter lower limit lo = int (input ('Enter starting number of the range: ')) # Prompt the user to enter upper limit hi = int (input ('Enter ending number of the range: ')) # Check validity of the input while ((lo < 1) or (hi < 1) or (lo > hi)): lo = int (input ('Enter starting number of the range: ')) hi = int (input ('Enter ending number of the range: ')) # Initialize variables to hold max cycle length and the corresponding number max_n = 0 max_length = 0 # Iterate over all numbers in the range for n in range (lo, hi + 1): # Initialize cycle length cycle_length = 0 # Use while loop to determine cycle length for n ... # Compare cycle length with max_length outside while loop if (cycle_length > max_length): max_length = cycle_length max_n = n # Write out the result ... main() ********************************************************************** # Solution of Samuel Pepys problem import random def main(): # number of trials num_trials = 1000 # trial 1: 6 throws of a fair die trial_1 = 0 for i in range (num_trials): is_one = 0 for j in range (6): if (random.randint(1, 6) == 1): is_one += 1 if (is_one >= 1): trial_1 += 1 print ('Trial 1: ', trial_1, '/', num_trials) # trial 2: 12 throws of a fair die trial_2 = 0 for i in range (num_trials): is_one = 0 for j in range (12): if (random.randint(1, 6) == 1): is_one += 1 if (is_one >= 2): trial_2 += 1 print ('Trial 2: ', trial_2, '/', num_trials) main()