Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.