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

"RAISE"-ing a question.

Cheers, fellow Treehousers.

In the video course on Raising Exceptions, in the Python Basics section of Python, I didn't quite fully grasp the exercise provided to us by Professor Craig Dennis.

The code runs perfectly for a division with negative numbers and division by 0. But let's imagine, "the user" when prompted with one of the two questions, decides to write a string. For example: My program - "How many people had dinner? " User - "5 but only 4 of us are paying."

They are displayed with the following, in my code: "We'll play later. Try again, please.
(In other words, invalid literal for int() with base 10: '5 but only 4 of us are paying.')."

Here goes an example of my program, in the text editor:

import math 

def split_check(total, num_of_people):
    if num_of_people <=1:
        raise ValueError("more than 1 person is required to split the check.")
    return math.ceil(total/ num_of_people)

try:
    total = float(input("What was the total of the dinner?  "))
    num_of_people = int(input("How many people had dinner?  "))
    amount_due = split_check(total, num_of_people)
except ValueError as err:
    print("We'll play later. Try again, please.")
    print("(In other words, {}).".format(err))
else:
    print("Each person owes ${}.".format(amount_due))

How can I fix this?

Thanks, Have a Great day.

[MOD - added ```python formatting -cf]

1 Answer

Chris Freeman, to not display this: "invalid literal for int() with base 10: '5 but only 4 of us are paying.')." when the user enters strings.

Chris Freeman
Chris Freeman
Treehouse Moderator 68,468 Points

Maybe I'm oversimplifying, but if you do not want to see the "invalid literal...." message, remove the line:

print("(In other words, {}).".format(err))

It is the value stored in err from the code as err that is being printed.