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():
chars = set('0123456789')
while True:
Class_A_Input = raw_input('Enter Class A tickets sold: ')
Class_B_Input = raw_input('Enter Class B tickets sold: ')
Class_C_Input = raw_input('Enter Class C tickets sold: ')
if any((c in chars) for c in Class_A_Input):
break
else:
print 'Wrong'
total_profit((int(Class_A_Input)), (int(Class_B_Input)), (int(Class_C_Input)))
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.
开发者_StackOverflow中文版Thanks for any help.
EDIT: I have put the code in now as I have it. I moved the 'int' to the 'total_profit' variable. How can I check all inputs?
def getInt(msg):
while True:
try:
return int(raw_input(msg))
except ValueError:
pass
def total_profit(a, b, c):
return 35.0*a + 25.0*b + 10.0*c
def main():
class_a = getInt('Enter Class A tickets sold: ')
class_b = getInt('Enter Class B tickets sold: ')
class_c = getInt('Enter Class C tickets sold: ')
print("Total profit is ${0:0.2f}.".format(total_profit(class_a, class_b, class_c)))
if __name__=="__main__":
main()
Python has tons of nifty functions. Here is one which I think shall help you:
> 'FooBar'.isdigit()
> False
> '195824'.isdigit()
> True
Calling int
on something that isn't a valid integer will raise a ValueError
exception. You can just catch that -- either each time you call int
, if you want to identify which input was invalid, or with a single try
around all three.
Or is there some further restriction you want that goes beyond that?
精彩评论