The Woo
The Woo

Reputation: 18675

Python - Check If Multiple String Entries Contain Invalid Chars

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

Answers (3)

kurumi
kurumi

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

David H. Clements
David H. Clements

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

Gareth McCaughan
Gareth McCaughan

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

Related Questions