错误检查:如检查负数,或输入不是数字。
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了错误检查:如检查负数,或输入不是数字。相关的知识,希望对你有一定的参考价值。
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')
我是新手,只是不明白当用户输入一个负数或一个字符串的数字时,我应该如何/在哪里使用“try”和“except”。
答案
也许尝试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 ()
以上是关于错误检查:如检查负数,或输入不是数字。的主要内容,如果未能解决你的问题,请参考以下文章