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

KRIS NIKOLAISEN
KRIS NIKOLAISEN
54,172 Points

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.