-1

I have tried making the input an integer but if I put a letter in I get the 'invalid literal for an int'

Please could you help.

def agecheck():

    quit_menu = False

    while quit_menu is False:

         age = input("\nEnter your age: ")

         if age >= "18":
             print("You are the correct age.")
         elif age < "18":
             print("Get off this website.")
         else:
             print("Enter a correct integer.")
             quit_menu = True

    agecheck()
Iguananaut
  • 21,810
  • 5
  • 50
  • 63

2 Answers2

0

Both the input and what you're comparing it to should be integers if using operators like >= or <. Additionally, I suspect you actually want to quit the menu if the input is valid as opposed to invalid, and continue looping until the user enters an integer. You should also make your code exception safe in the event that something is entered that cannot be cast as an int. Try the following:

def agecheck():

    quit_menu = False

    while quit_menu == False:

         try:

             age = int(input("\nEnter your age: "))

             if age >= 18:

                 print("You are the correct age.")

             elif age < 18:

                 print("Get off this website.")

             quit_menu = True

         except:

             print("Enter a correct integer.")

agecheck()
Erick Shepherd
  • 1,403
  • 10
  • 19
  • I tried that code but I entered a letter and I got this error: `ValueError: invalid literal for int() with base 10: 'a'` Is there a way to fix it? – Benjamin Higgs Nov 02 '17 at 18:28
  • @BenjaminHiggs I was actually editing it just before you posted. See my last edit. You need to make your code exception safe. – Erick Shepherd Nov 02 '17 at 18:29
  • Ok, thanks. I just needed it as my teacher asked if I could put all my programs in a menu system. – Benjamin Higgs Nov 02 '17 at 18:30
  • @BenjaminHiggs No problem! If this was the answer you were looking for, don't forget to hit the "accept answer" button. Let me know if you have any other questions! – Erick Shepherd Nov 02 '17 at 18:31
0

Here's something you can try -

def agecheck():
  ans = input("\n Enter your age: ")
  try:
    age = int(ans)
    if age >= 18:
      print("You are the correct age.")
    elif age < 18:
      print("Get off this website.")
    else:
      print("Enter a correct integer.")
  except ValueError:
    print("That wasn't a number")


for i in range(3):
  agecheck()

It runs three times, enter the inputs 4, 20, and "a", and notice the logs.

Manish Giri
  • 3,562
  • 8
  • 45
  • 81