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 Python Basics Functions and Looping Raising Exceptions

That code bring up the message "(could not convert string to float: 'too') " If you type in letters. How to fix?

import math

def split_check(total, number_of_people):
    if number_of_people <= 1:
        raise ValueError("Please enter 2 or more")
    return math.ceil(total / number_of_people)
try:
    total_due = float(input("What is the total?  "))
    number_of_people = int(input("How many people?   "))
    amount_due = split_check(total_due, number_of_people)
except ValueError as err:
    print("Numbers only please :)")
    print("({})".format(err))
else:     
    print("Each person owes {}.".format(amount_due))
```python

1 Answer

Asher Orr
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Asher Orr
Python Development Techdegree Graduate 9,410 Points

Hi Blair! In order for Python to perform the math in your split_check function, it needs to work with integers.

Look at your try block: total_due is set by asking for user input.

User input is always a string, because the input () function always returns string values.

total_due = float(input("What is the total?  "))

The line above accepts user input, which is a string, then attempts to convert it to a floating point number. If Python sees that the string represents a number, like "1", it will convert it to a floating point number. But if not, it will raise a ValueError.

except ValueError as err:
    print("Numbers only please :)")
    print("({})".format(err))

If the user enters something that can't be converted to a floating point number, like the string "too", the code will print "Numbers only please :)," followed by the message from the Python interpreter (that's the "err.")

except ValueError as err:
    print("Numbers only please :)")
    #the script prints the message above
    print("({})".format(err))
    #then it prints the error message from Python

It's not an error with the code. Your code is working exactly as intended! It's designed to give users an error message they can understand IF they make a "user input error."

Does this answer your question?