Search code examples
pythonuser-input

ValueError: invalid literal for int() with base 10: 'quit'


I keep getting this errror message:

ValueError: invalid literal for int() with base 10

Here is my code snippet

age = {} 
while age != 'quit': 
      age = input('what is your age?') 
      age = int(age) 
      if age >= 18: 
        print("You're old enough to vote.") 
      else: 
        print("You're not old enough to vote.")

Please use **Google Colab **if possible.

I tried the `except ValueError method but it did not work. Maybe I just used it incorrectly:


Solution

  • One of the approach (may not be optimal) is to break the loop once you encounter ValueError. Logic can be similar to this

    while age != 'quit':
        age = input()
        try:
            age = int(age)
            if age >= 18:
                print("You're old enough to vote.")
            else:
                print("You're not old enough to vote.")
        except ValueError:
            break