Python 我想对int()进行输入验证,但对str()进行验证
当用户的输入为时,我希望代码“中断”,因为计算的第一个条件是Python 我想对int()进行输入验证,但对str()进行验证,python,validation,debugging,python-3.x,optimization,Python,Validation,Debugging,Python 3.x,Optimization,当用户的输入为时,我希望代码“中断”,因为计算的第一个条件是int(x)您将获得ValueError,因为您无法将字符串'stop'转换为整数 解决此问题的一种方法是使用帮助器方法,该方法正确捕获ValueError,然后检查字符串是否为stop: def should_stop(value): try: return int(value) <= 0 except ValueError: return value.lower() == "st
int(x)您将获得ValueError
,因为您无法将字符串'stop'
转换为整数
解决此问题的一种方法是使用帮助器方法,该方法正确捕获ValueError
,然后检查字符串是否为stop
:
def should_stop(value):
try:
return int(value) <= 0
except ValueError:
return value.lower() == "stop"
while True:
x = input("how many times do you want to flip the coin?: ")
if should_stop(x):
break
def应停止(值):
尝试:
返回int(值)
if int(x) <= 0 or str(x).lower() == "stop":
ValueError: invalid literal for int() with base 10: 'stop'
if x.lower() == 'stop' or int(x) <=0
def should_stop(value):
try:
return int(value) <= 0
except ValueError:
return value.lower() == "stop"
while True:
x = input("how many times do you want to flip the coin?: ")
if should_stop(x):
break