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

Please help! I can't get an exception for the total bill amount to work

Hi,

I'm trying raise an exception when the total bill amount entered by the user is <=0, but I can't get it to work. However, the below code does work in raising an exception for the number of guests. Please can someone tell me where I'm going wrong and how to get it right?

Cheers Zak

import math

def split_cheque(total, guests): if total <=0: raise ValueError("The bill must be more than 0!") elif guests <=1: raise ValueError("More than 1 person is required to split the cheque.") return math.ceil(total / guests)

try: total = float(input("What is the total bill amount? ")) guests = float(input("How many guests are there? ")) amount_due = split_cheque(total, guests) except ValueError as err: print("Oh no! That's not a valid value... Please try again.") print("({})".format(err)) else:
print("The cost per guest is £{}. Many thanks!".format(amount_due))

1 Answer

Eric M
Eric M
11,545 Points

Hi Zak,

I've set your code out as follows and both exceptions get thrown for me. What issues are you having?

import math


def split_cheque(total, guests):
        if total <=0:
                raise ValueError("The bill must be more than 0!")
        elif guests <=1:
                raise ValueError("More than 1 person is required to split the cheque.")

        return math.ceil(total / guests)


try:
        total = float(input("What is the total bill amount? "))
        guests = float(input("How many guests are there? "))
        amount_due = split_cheque(total, guests)
except ValueError as err:
        print("Oh no! That's not a valid value... Please try again.")
        print("({})".format(err))
else:
        print("The cost per guest is £{}. Many thanks!".format(amount_due))

Separately, let me suggest that you either change the parameter names in split_cheque or the variable names in your try block so that the total and guests parameters in split_cheque aren't shadowing names from the outer scope? You could also wrap your try/except block in a function then call that function in the outer scope to avoid this.

Cheers,

Eric

pet
pet
10,908 Points

Your code works in workspace. :)