Search code examples
python-3.xexceptionerror-checking

Error checking: like checking for negative numbers, or input that's not a number.


weight=input('What is your weight?')
age=input('What is your age?')
w=int(weight)
a=int(weight)
if (a<=10 and w<80):
  print('This person needs to ride the black roller coaster')
if (a<=10 and 80<=w<=200):
  print('This person needs to ride the green roller coaster')
if (a<=10 and w>200):
  print('This person needs to ride the yellow roller coaster')
if (10<a<=20 and w<80):
  print('This person needs to ride the silver roller coaster')
if (10<a<=20 and 80<=w<=200):
  print('This person needs to ride the red roller coaster')
if (10<a<=20 and w>200):
  print('This person needs to ride the purple roller coaster')
else:
  print('This person needs to ride the pink roller coaster')

I'm new to this and just don't understand how/where I'm supposed to use "try" and "except" for when the user inputs a number that's negative or a string.


Solution

  • Maybe try try like this:

    def checkValue():
    while True:
        try:
            global a, w
            a = int(input("What's your age? ").strip())
            w = int(input("What's your weight? ").strip())
        except ValueError as e:
            print("This is not a number. Try again.")
            continue
        if a <= 0 and w <= 0:
            print("Enter value lager than 0.")
            continue
        else:
            break
        return a, w
    
    checkValue ()