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 trialzoltans
2,547 Pointsnegative value for bill amount
In this video Craig didn't mention what happens if the user enters a negative value for bill_total. It took me a while to try to figure out where to place an "if bill_total <= 0:" statement, and how to call it. I'm not sure I have written this line of code to the right place. The code runs fine, but could I have done something differently? Can someone with more experience, check if my solution is correct, and if it's the right way to create a definition for this particular project and for this negative bill amount issue? Thanks a lot
import math
def split(bill, people):
if people <= 1:
raise ValueError("More than one required...")
return math.ceil(bill / people)
try:
bill_total = float(input("Total bill: £"))
if bill_total <= 0:
raise ValueError("Bill amount must be more than £0")
people = int(input("How many people? "))
amount_due = split(bill_total, people)
except ValueError as err:
print("Oh, no! That's not a valid value. Please, try again...")
print("{}".format(err))
else:
amount_due = split(bill_total, people)
print("Each person owes £{}".format(amount_due))
1 Answer
Brandon Kuske
4,269 PointsThat looks good to me. Computers can handle negative values in strange ways so it's always good to proof against those issues.
Justin Cox
12,123 PointsJustin Cox
12,123 PointsYou got it! Asking yourself if you could have achieved the same result in another, more effective way, is a great programming mindset by the way, so kudos for that!
Where you placed your code seems to be the most effective. You could arguably place it inside the
split
function, since both conditions are semantically related to splitting a bill. The only problem is (as I can tell you've caught!), the program would allow the user to enter $0 or less for the bill, still ask how many people to split the bill, and only then would it say it can't do that. So where you have your code seems to be the most effective place, halting the program as soon as they enter $0 or less! Great job!