1

I'm trying to build a vaccine tracker for my apartment complex. When I'm trying to test the below code in jupyter-notebook I receive following error when I use non integer inputs.

Ask: What's the best solution to resolve this error? I'm a complete beginner in python and trying to learn and practice at the same time.

Error:

ValueError Traceback (most recent call last) in 2 print("2.Covaxin") 3 ----> 4 vaccine_type = int(input("Select a number - ")) 5 if vaccine_type ==1: 6 covishieldData

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

Code:

print("1.Covishield")
print("2.Covaxin")
    
vaccine_type = int(input("Select a number - "))
if vaccine_type ==1:
  covishieldData
elif vaccine_type ==2:
  covaxinData
else: 
  print("Invalid Input - Please enter either 1 or 2 to proceed further")
  • 1
    Did you put `a` when you are prompt to input for `Select a number - `? – kennysliding Jun 20 '21 at 18:40
  • Yes. As it's user input anyone can accidentally put a or b or any special characters. I want to ensure (Validation loop for every wrong input, till user selects the correct input). Once the correct input is selected then move to next function – Apekshit Dhoke Jun 20 '21 at 23:18

2 Answers2

1

You will need an error checking for your input before passing the input into the next steps.

A common practice is to use a loop with try-except to wrap the prompt until the input is valid.

while True:
    try:    
        vaccine_type = int(input("Select a number - "))
        if vaccine_type != 1 and vaccine_type != 2:
            raise ValueError
        break
    except ValueError:
        print("Invalid Input - Please enter either 1 or 2 to proceed further")
...
kennysliding
  • 2,783
  • 1
  • 10
  • 31
0

Please read a bit documentation before you use any functions. If you are not aware of what a function is, read here.

The error or exception(not normal behaviour) which you are getting is because while passing input to in-built input function, you are passing the character a, then the in-built function int tries to convert this string a to integer with base 10. Since a is not a valid integer, hence the python interpreter throws this exception/error.

Please use checks as burringalc recommended in other answer and make sure it could be converted to a valid integer or make sure you only pass input as 1 or 2, since you only wish to check for 1 or 2 as an input.

gmatharu
  • 83
  • 1
  • 8