我是python的新手,也遇到过这个问题。这个程序的作用是询问用户的年龄。年龄必须是一个数字,否则它将返回一个值错误。我已经使用try/except方法来响应错误,但是我也希望它能够让用户输入的年龄低于一个特定的值(例如200)。你知道吗
while True:
try:
age=int(input('Please enter your age in years'))
break
except ValueError:
print ('\n\n\n\nThat\'s not a valid Number.\nPlease try Again.\n\n\n\n')
except:
if age>=200:
print ('\n\n\n\nThat\'s not a valid Number.\nPlease try Again.\n\n\n\n')
print (f'Your age is {age}')
我试过这个还有其他东西。有人能帮忙吗?你知道吗
您可以在
input()
之后执行if
语句,仍然保留except ValueError
,例如:可能的解决方案:
在这种情况下,不需要进行异常处理。你知道吗
isdigit()
是字符串对象的方法,它告诉您给定的字符串是否只包含数字。你知道吗首先需要检查输入的值是否为整数,请在try子句中执行此操作。 然后需要检查该值是否在范围内,在else子句中执行此操作,该子句仅在try块成功时执行。
如果值在范围内,则中断。 下面的代码显示了这一点。你知道吗
相关问题 更多 >
编程相关推荐