ShadyBears
ShadyBears

Reputation: 4175

Try and except in Python, unexpected output

EDIT: Changed conditional.. thanks

I'm trying to learn the try/exception. I am not getting the output I should be. It usually makes one cup or none. Ideally, it should make 9 or 10.

Instructions:

Create a NoCoffee class and then write a function called make_coffee that does the following: use the random module to with 95% probability create a pot of coffee by printing a message and returning as normal. With a 5% chance, raise the NoCoffee error.

Next, write a function attempt_make_ten_pots that uses a try block and a for loop to attempt to make ten pots by calling make_coffee. The function attempt_make_ten_pots must handle the NoCoffee exception using a try block and should return an integer for the number of pots that are actually made.

import random

# First, a custom exception
class NoCoffee(Exception):
    def __init__(self):
        super(NoCoffee, self).__init__()
        self.msg = "There is no coffee!"

def make_coffee():
    try:
        if random.random() <= .95:
            print "A pot of coffee has been made"

    except NoCoffee as e:
        print e.msg

def attempt_make_ten_pots():
    cupsMade = 0

    try:
        for x in range(10):
            make_coffee()
            cupsMade += 1

    except:
        return cupsMade


print attempt_make_ten_pots()

Upvotes: 1

Views: 228

Answers (1)

thefourtheye
thefourtheye

Reputation: 239443

  1. If you want to allow 95% then the condition should have been

    if random.random() <= .95:
    
  2. Now, to make your program throw an error and return the number of coffees made, you need to raise an exception when the random value is greater than .95 and it should be excepted in the attempt_make_ten_pots function not in make_coffee itself.

    import random
    
    # First, a custom exception
    class NoCoffee(Exception):
        def __init__(self):
        super(NoCoffee, self).__init__()
        self.msg = "There is no coffee!"
    
    def make_coffee():
        if random.random() <= .95:
            print "A pot of coffee has been made"
        else:
            raise NoCoffee
    
    def attempt_make_ten_pots():
        cupsMade = 0
        try:
            for x in range(10):
                make_coffee()
                cupsMade += 1
        except NoCoffee as e:
            print e.msg
        return cupsMade
    
    print attempt_make_ten_pots()
    

Upvotes: 4

Related Questions