Reputation: 19
I am using Python 3.0. I'm trying to ask the user to enter the string 'Small', 'Medium' or 'Large' and raise an error if none of those are entered and then ask for input again.
while True:
try:
car_type = str(input('The car type: '))
except ValueError:
print('Car type must be a word.')
else:
break
Why doesn't this work? Even if a number is entered the program continues and comes to an error at the end.
Upvotes: 1
Views: 3299
Reputation: 117681
input
always returns a str
, so str(input())
never raises a ValueError
.
You're confusing a string with a word. A string is just a series of characters. For example "123hj -fs9f032@RE#@FHE8"
is a perfectly valid sequence of characters, and thus a perfectly valid string. However it is clearly not a word.
Now, if a user types in "1234", Python won't try to think for you and turn it into an integer, it's just a series of characters - a "1" followed by a "2" followed by a "3" and finally a "4".
You must define what qualifies as a word, and then check the entered string if it matches your definition.
For example:
options = ["Small", "Medium", "Large"]
while True:
car_type = input("The car type: ")
if car_type in options: break
print("The car type must be one of " + ", ".join(options) + ".")
Upvotes: 1
Reputation: 238159
You can simply do as follows:
valid_options = ['Small', 'Medium' , 'Large' ]
while True:
car_type = input('The car type: ') # input is already str. Any value entered is a string. So no error is going to be raised.
if car_type in valid_options:
break
else:
print('Not a valid option. Valid options are: ', ",".join(valid_options))
print("Thank you. You've chosen: ", car_type)
There is no need for any try and error here.
Upvotes: 1