Here are some examples:
Monte Carlo pi computation from Day 6 but using Ctrl-C to exit:
import random
import math
# A Monte Carlo simulation to calculate pi by picking random points and computing
# how many fall inside the unit circle.
print("Press Ctrl-C to exit")
try:
numInside = 0.0
numIterations = 0
while True:
# generate a random point in the first quadrant
x = random.random()
y = random.random()
# compute distance to the origin
dist = math.sqrt(x**2 + y**2)
numIterations += 1
if dist <= 1:
numInside += 1
except KeyboardInterrupt:
# we multiply by 4 since we are only testing the first quadrant
print("There were %i iterations" % numIterations)
print("pi = %f" % (numInside / numIterations * 4))
input("Press enter to exit")
An example with multiple try/except blocks. Try entering non-numbers and entering a zero denominator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
|
The following shows the input and output of one run of the divide code above where I typed in some values for the input. For this run of the code, describe the order in which python ran the program by listing the line numbers of the lines of code in the order they were executed, starting with line 1.
Enter the numerator: abc
That wasn't a number!
I am the finally block
Enter the numerator: 100
Enter the denominator: abc
That wasn't a number!
I am the finally block
Enter the numerator: 50
Enter the denominator: 0
I am the finally block
An exception occured
integer division or modulo by zero
Press enter to exit