How to make users only enter integer values in Python program

后端 未结 5 1333
别跟我提以往
别跟我提以往 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:43
    while True:
        try:
           amount=int(input("how many do you want to buy"))
           break
        except ValueError:
           print("Please Enter An Amount")
           continue
        else:
            break
    

    This is a simple way of making the user inputs an integer in python 3. This can also be for making sure the user inputs a string all you need to do for this is just change int(.into str(

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-20 07:48

    Let the user enter anything he wishes, and warn only if it wasn't an integer:

    try:
        num = int(input("enter number: "))
    except ValueError:
        print("you must enter an integer")
    

    This is the Pythonic way to do it, after all it's "Easier to ask forgiveness than permission".

    0 讨论(0)
  • 2020-12-20 07:59

    Yes this could be a while loop such as

    while 1:
      instr = input('Enter an integer')
      try:
        val = int(instr)
        print 'integer entered', val
        break
      except ValueError:
        print instr, ' is not an integer'
    
    0 讨论(0)
  • 2020-12-20 08:02

    I normally put the text outside and wrap it like a function to make it similar to the standard input. Maybe someone likes it:

    def int_input(text):
        """Makes sure that that user input is an int"""
        while True:
            try:
                num = int(input(text))
            except ValueError:
                print("You must enter an integer.")
            else:
                return num
    
    user_int = int_input("Enter a number: ")
    
    0 讨论(0)
提交回复
热议问题