Nov 6

Lecture Overview

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
def divide():
    "A function to prompt the user to divide two numbers"

    # Loop until the return statement below
    while True:

        try:
            # If the int conversion fails, python will raise the ValueError exception
            # jump immediately to the body of the "except" block below.
            num = int(input("Enter the numerator: "))
            denom = int(input("Enter the denominator: "))

            # If denom is zero, python will raise the DivideByZero exception.  This will cause the function
            # to be aborted (but not before the finally block is run).
            result = num / denom

            # If the division worked correctly, we will return normally.  The finally block is still executed
            # before the return from this function happens
            return result

        except ValueError:
            # If an exception was raised, it is handled here 
            print("That wasn't a number!")

        finally:
            print("I am the finally block")

try:
    f = divide()
    print(f)
except Exception as e:
    print("An exception occured")
    print(e)

input("Press enter to exit")

Exercises

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