错误检查:如检查负数,或输入不是数字。

时间:2018-03-06 07:29:13

标签: python-3.x exception error-checking

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')

我对此很陌生,只是不明白我应该如何使用&#34;尝试&#34;和&#34;除了&#34;当用户输入一个负数或字符串的数字时。

1 个答案:

答案 0 :(得分:1)

也许像这样试试try

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 ()