0

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.

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?

2
  • 1
    Why have you asked both this question and the nearly-identical stackoverflow.com/questions/5439731/… ? Commented Mar 26, 2011 at 1:43
  • Flagging as duplicate... Commented Mar 26, 2011 at 1:45

3 Answers 3

2
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()
Sign up to request clarification or add additional context in comments.

Comments

1

Python has tons of nifty functions. Here is one which I think shall help you:

> 'FooBar'.isdigit()
> False

> '195824'.isdigit()
> True

Comments

1

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.