Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Example Code Doesn't Work With "ZeroDivisionError"

I'm sure in the next video he explains a better method. But I tried to handle the ZeroDivisionError if someone enters a "0" for the second input. My code is below and doesn't work. It still displays the ZeroDvisionError and won't print my statement.


import math

def split_check(total, number_of_people): return math.ceil(total / number_of_people)

try: total_due = float(input("What is the total?: ")) number_of_people = int(input("How many people?: ")) except ValueError: print("Oh no! That's not a valid value. Try again...") except ZeroDivisionError: print("Oh no! You can't have a $0 bill. Please enter a different amount... ") else: amount_due = split_check(total_due, number_of_people) print("Each person owes ${}".format(amount_due))

1 Answer

Phil Livermore
Phil Livermore
11,018 Points

You need the try on the calculation only and not the input values etc. Also having a $0 value does not throw a value error as it is not an error to divide 0 by something, only to divide something by 0. Something like this will work and propbably helps you understand as it is closer to your code but there are probably tidyer ways to do it but you will learn that as you progress.

import math

def split_check(total, number_of_people):
    return math.ceil(total / number_of_people)

total_due = float(input("What is the total?: "))
number_of_people = int(input("How many people?: "))
try:
    amount_due = split_check(total_due, number_of_people)
    if total_due > 0.0:
        print("Each person owes ${}".format(amount_due))
    else:
        print("Oh no! You can't have a $0 bill. Please enter a different amount... ")
except ZeroDivisionError:
    print("Oh no! You can't have 0 people")