pythonpython-3.xinteger

How to make users only enter integer values in Python program


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 tell them how many boxes (of six eggs) that they can fill and how many eggs are left over.

I need to make sure that if the user enters a non integer value, an error message will be displayed. I can't figure out how to do this and any help would be much appreciated! Is it something to do with while loops or am I completely wrong?


Solution

  • 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".