Wanting to add TEXT input as a value error

Hi All
I am asking the user to input a number from 1 to 5 in menu, but if they type text in by mistake, it crashes the programme. I have an invalide number covered, with a user error message:
else:
print(“Invalid option, please select 0 to 5”)

But I am not sure how to add any text input as an error, as my simple programme only requires numbers (int) to be entered

here is my full code:

  import time
  
  def menu():
      print("***Welcome to City Gym main menu***")
      print()
      print("[1] Calculate body mass index BMI")
      print("[2] Veiw membership cost")
      print("[0] Exit the program.")
  
  menu()
  option = int(input("Please enter your option: "))
      
  time.sleep(1)
  
  while option != 0:
      if option == 1:
          Height = float(input('Please enter your height in meters: '))
          print("Processing...")
          time.sleep(1)
          Weight = float(input('Please enter your weight in kilograms: '))
          print("Processing...")
          time.sleep(1)
  
          def BMI(Height, Weight):
                  BMI = round(Weight/(Height**2),3)
  
                  if (BMI < 18.5):
                          return 'Underweight', BMI
                  elif (BMI >= 18.5 and BMI < 25):
                          return 'Normal', BMI
                  elif (BMI >= 25 and BMI < 30):
                          return 'Overweight', BMI
                  elif (BMI >= 30):
                          return 'Obese', BMI
          quote, BMI = BMI(Height, Weight)
          print('Your BMI is: {} and you are: {}'.format(BMI, quote))
  
          anykey=input("Enter any key to return to main menu: ")
          print()
          menu()
  
      elif option == 2:
          def package():
                  print()
                  print("***Welcome to City Gyms Member page***")
                  print()
                  print("[1] Our BASIC membership package")
                  print("[2] Our REGULAR membership package")
                  print("[3] Our PREMIUM membership package")
                  print("[4] Return to MAIN menu")
                  print("[5] Exit the programme")
  
          while True:
              package()
              option = int(input("Please enter your option: "))
              print("Processing...")
              time.sleep(1)
              if option == 1:
                  print("Our BASIC membership cost is $10 per week")
                  base_weekly_cost = 10
                  base_weekly_cost = base_weekly_cost * 4
  
                  print("The monthly cost will be, $" + str(base_weekly_cost))
              elif option == 2:
                  print("Our REGULAR membership cost is $15 per week")
                  base_weekly_cost = 15
                  base_weekly_cost = base_weekly_cost * 4
  
                  print("The monthly cost will be, $" + str(base_weekly_cost))
              elif option == 3:
                  print("Our PREMIUM membership plan costs $20 per week")
                  base_weekly_cost = 20
                  base_weekly_cost = base_weekly_cost * 4
  
                  print("The monthly cost will be, $" + str(base_weekly_cost))
              elif option == 4:
                  print("Hold on 2 seconds, returning you to the MAIN menu......")
                  menu()
                  break
              elif option == 5:
                  print("Thank you for using my menu programme.")
                  quit()
              
              else:
                  print("Invalid option, please select 0 to 5")
                  
              anykey=input("Enter any key to return to membership menu: ")
  
      else:
          print("Invalid option, please select 0 to 2")
  
      print()        
      menu()
      option = int(input("Please enter your option: "))
  print("Processing...")
  print()
  print("Thank you for using my menu programme.")

I am asking the user to input a number from 1 to 5 in menu, but if they
type text in by mistake, it crashes the programme. I have an invalide
number covered, with a user error message:

           else:
                           print("Invalid option, please select 0 to 5")

Looking at your code, i think it would make this complains about option
0 as well :slight_smile:

But I am not sure how to add any text input as an error, as my simple programme only requires numbers (int) to be entered

here is my full code:
[…]
option = int(input("Please enter your option: "))

I expect that this is the line where you get the exception? It would be
good if you had included the full exception traceback to make that
clear.

You need to handle that exception. The normal way of doing that is a
try/except, like this:

 try:
     option = int(input("Please enter your option: "))
 except ValueError:
     print("Invalid non-integer input, please select 0 to 5")
     continue
 ... the rest of the loop body here ...

Cheers,
Cameron Simpson cs@cskk.id.au

Thanks Cameron
I just put that in and get an error:
Traceback (most recent call last):
File “c:\Users\vince\work\Assessment 1\Assessment 1 WORKING2 Try and except work.py”, line 19, in
while option != 0:
^^^^^^
NameError: name ‘option’ is not defined

I placed the try and except into line 12 of the code. Any thoughts?

Hi Cameron
I solved it lol!

1 Like