While loops - mrprov12/DSPrep GitHub Wiki
while loops
You should only use a while loop when the number of iterations of the loop is not known.
def greatest_common_divisor(num_1, num_2):
"""
Calculate the Greatest Common Divisor of num_1 and num_2.
"""
runs = 0
while num_2 != 0:
runs += 1
num_1, num_2 = num_2, num_1 % num_2
print(runs, ' iterations')
return num_1
print(greatest_common_divisor(121, 55))
print(greatest_common_divisor(75, 50))
print(greatest_common_divisor(999, 33))
print(greatest_common_divisor(27, 17))
watch out for infinite while loops, add in breaks when certain conditions are met to avoid
# define a counter
loops = 0
# notice that setting x to 2 will allow entrance into the while
x = 2
# put the counter in the `while` to avoid an infinite loop
while x < 3:
print(x)
# this condition will ensure that the while exits
if loops > 20:
break
# make sure to increment the loops variable
loops += 1
while loop using conditional check:
while True: do something x = 20
while x > 0:
print(x)
x -= 1
another example:
def get_menu_item(): menu = '''Choose an item: (1) broccoli (2) carrots (3) cabbage choice: '''
choice = int(input(menu))
items = ['broccoli', 'carrots', 'cabbage']
return items[choice-1]
orders = []
cont = 'y' while cont == 'y': orders.append(get_menu_item())
# order_max -= 1
cont = input('order more? ')
print(orders)
open-ended problems:
from random import choice
def get_sample(lower=1, upper=100):
return choice(range(1, upper+1))
def get_sample_counts(m, threshold):
output = []
for _ in range(m):
num_trials = 1
while True:
sample = get_sample()
if sample < threshold:
output.append(num_trials)
break
else:
num_trials += 1
return output
sample_trials = get_sample_counts(100, 25)
# Make the index of counts correspond with the
# number of trials
counts = [0]*(max(sample_trials) + 1)
for trial in sample_trials:
counts[trial] += 1
# Make a simple terminal graphic to display the distribution
# of number of trials needed to achieve a value
# below a given threshold.
for i, count in enumerate(counts):
if i == 0:
continue
print('{:4d}: {}'.format(i, '*' * count))
for or while?
The previous lessons have talked extensively about when to not use a while loop. Essentially, avoid using while loops, unless they are specifically appropriate.
####while for menus and open-ended problems
When you need to create a menu but you don't know how many selections will need to be made from that menu, a while loop is very appropriate. In addition, if you don't know how long your algorithm will need to run to be able to solve a particular problem, then a while loop is likely an appropriate approach.
####for loops if you know how many times the loop should run
In many cases you will use a for loop to traverse a list. If you have a populated list, then you know how many items are in that list, which means you most likely know how many times your loop should run. In these cases, you will almost always use a for loop.
In other cases, you may use a for loop to perform an action some x number of times. You can use for i in range(x): do something to perform this operation.