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 All Together Now Handle Exceptions

Friedrich Dalman
Friedrich Dalman
1,502 Points

How to detect if value entered for number of tickets is not 4 but is the word four so we can give the correct message ?

In this script if the user enters "four" for the question how many tickets would you like, it will generate a ValueError because four cannot be coerced into an integer. So how can we detect that a word like four has been enter in response to the prompt "how many..." so that we can create a ValueError with the message "you must enter a number, a word won't work with this program" instead of the unfriendly "invalid literal for int()..." message?

1 Answer

Since valid input is a positive integer you could use the isdigit() method. This returns True if all characters in the string are digits. Use this with an if statement before attempting to convert the input to an integer.

Or if you are specifically looking to see if the input is a number word then you could install a module like word2number and use its word_to_num method to see if a number is returned.