How to make users only enter integer values in Python program

后端 未结 5 1349
别跟我提以往
别跟我提以往 2020-12-20 07:33

I have a homework assignment that I am very confused about. I have to write a program allowing users to input the number of eggs that they are buying. The program will then

5条回答
  •  春和景丽
    2020-12-20 07:47

    [EDIT] My comment and code is valid only for python 2.x.

    Contrary to other answers you should almost never use 'input()' when asking users, but rather 'raw_input()'.

    'input()' evaluates string that it got from user, like it was part of program. This is not only security issue, but is unpredictable and can raise almost any exception (like NameError if python will try to resolve a letter as variable name).

    num = None
    while num is None:
        try:
            num = int(raw_input("Enter an integer: "))
        except ValueError:
            print 'That was not an integer!'
            affirmations = ('YES', 'Y')
            answer = raw_input("Do you want to continue? (Yes/Y/y):\n")
            if answer.strip().upper() in affirmations:
                continue
            else:
                break
    print num
    

提交回复
热议问题