Python Forum

Full Version: why does integer input give error invalid literal for int()
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am keep getting an error if I put in something other than an integer. I want the loop to reiterate if say enter is pushed or if a letter is input. I want to give the user the error message I put in the else statement and return back to asking for the input again. Thank you.  

pizza_high = 0
      
      while not repeat:
        pizza_high = int(input('How many pizzas would you like to order:'))
        if pizza_high != int:
          repeat = True
        else:
          print('**ERROR** Please use whole numbers only!!')
          pizza_high = 0
      for x in range(0, pizza_high): 
        print('pizzas')
This is the input if "5" was selected, it works properly.

How many pizzas would you like to order: 5
    pizzas
    pizzas
    pizzas
    pizzas
    pizzas
    

However if I hit enter or put in a letter it gives this error

   
How many pizzas would you like to order: t
    ValueError: invalid literal for int() with base 10: ';'
Use a try/except instead of in if block, since int() throws errors if you try to convert something that can't be converted:
>>> int("43")
43
>>> int("four")
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'four'

>>> try:
...   num = int("43")
... except ValueError as err:
...   print("That's not a number...")
...   print(err)
...
>>> num
43
>>> try:
...   num = int("four")
... except ValueError as err:
...   print("That's not a number...")
...   print(err)
...
That's not a number...
invalid literal for int() with base 10: 'four'
You should go and read about exception handling, as that's often used to signal errors in Python. We say that int() raises an exception of type ValueError when its argument can't be converted to an integer. So, as shown above, the solution is to handle or catch the ValueError with try and except.

Line 5 in your code is also wrong - you're trying to compare the value of pizzas with the function int(), which makes no sense.