Exercises for Lesson 16
Exercise 1: break versus continue
What values are printed in each of the following loops?
for i in range(10):
if i == 3:
break
print(i)
for i in range(10):
if i == 3:
continue
print(i)Exercise 2: Rolling random dice, revisited
Part a: Updating your diagram
The following program is a modification to the dice-rolling program from Lesson 15. How does the diagram we drew need to change based on the changes? (Hint: Look for # new!.)
import random
from matplotlib import pyplot as plt # new!
def getInputs():
return int(input("How many dice? "))
def rollD4():
return random.randint(1,4)
def rollDice(n):
counts = [0]*4
for i in range(n):
val = rollD4()
counts[val-1] += 1
return counts
def printResults(rolls):
for i in range(len(rolls)):
rollCount = rolls[i]
print(i+1, rollCount, rollCount / sum(rolls))
def graphResults(rolls): # new!
plt.figure()
plt.pie(rolls, labels=[1,2,3,4], autopct="%1.2f%%")
plt.show()
def main():
n = getInputs()
diceRolls = rollDice(n)
printResults(diceRolls)
graphResults(diceRolls) # new!
if __name__ == "__main__":
main()Part b: Graphing results
Let’s dive into these changes a bit.
The library Matplotlib makes it incredibly easy to visualize data. If you don’t have it already, you can get it from the command prompt (search “cmd” in Windows or “Terminal” on a Mac), with the following command:
pip3 install matplotlibThen, try to run this modified dice-rolling program. It should both print the results and display a pie chart. You can play around with the labels or the value of n to see how the pie chart changes. You can also look at Matplotlib tutorials to find out how to customize the plot with a title, legend, etc.
Here is an example pie chart:

Part c: A different graph
How would you draw a bar graph instead of the pie chart? Explore the Matplotlib examples to find a relevant code sample.
Part d: A different die
How would you change the code to support a six-sided die? What about a twenty-sided die? What about drawing different subplots for different values of n?
Exercise 3: Rolling unfair dice
We talked about the following function, which effectively flips an unfair coin, one that comes up heads with probability prob. Here is that flipCoin function:
def flipCoin(prob):
val = random.random()
if val < prob: # less than so that it is exactly prob% of the range [0,1)
return "heads"
else:
return "tails"How can you change the four-sided-dice-rolling program to allow for weighted dice? Before writing any code, think carefully about which functions would need to change to support, for example, a die that comes up 4 approximately 40% of the time, and each of 1, 2, or 3 approximately 20% of the time.