Reputation: 18675
Using Python v2.x, I have 3 variables that I want to ask the user for, as below:
def Main():
Class_A_Input = int(raw_input('Enter Class A tickets sold: '))
Class_B_Input = int(raw_input('Enter Class B tickets sold: '))
Class_C_Input = int(raw_input('Enter Class C tickets sold: '))
How can I check if the user input is a valid input. IE: I want only numerical data entered. I have done this once before using 'chars = set('0123456789') and the 'WHILE' functions, but cannot seem to get it to work for multiple inputs.
Thanks for any help.
Upvotes: 0
Views: 297
Reputation: 25609
Or you can omit the use of int(), and check the Class_A_input
using isdigit()
>>> "asdf1".isdigit()
False
>>> "123".isdigit()
True
Upvotes: 0
Reputation: 3638
import sys
try:
Class_A_Input = int(raw_input('Enter Class A tickets sold: '))
except ValueError:
print "First input was not a number."
sys.exit(1)
Will this pattern work for your use case?
Upvotes: 0
Reputation: 19981
Calling int
on something that isn't a valid integer will raise a ValueError
exception. You can just catch that. Or is there some further restriction you want that goes beyond that?
Upvotes: 2