[英]I want to do an input validation on an int(), but validate for str()
I want the code to "break" when the user's input is <=0 AND when the input = "stop". 当用户的输入<= 0且输入=“停止”时,我希望代码“中断”。 This is what I have so far. 这就是我到目前为止所拥有的。
while True:
try:
x = input("how many times do you want to flip the coin?: ")
if int(x) <= 0 or x.lower() == "stop":
break
x = int(x)
coinFlip(x)
except ValueError:
print ()
print ("Please read the instructions carefully and try one more time! :)")
print ()
I get the error: 我收到错误:
if int(x) <= 0 or str(x).lower() == "stop":
ValueError: invalid literal for int() with base 10: 'stop'
you get the exception because the first condition that's evaluated is int(x) <= 0
and x is not really an integer at this point. 你得到异常是因为第一个被评估的条件是int(x) <= 0
而x此时并不是真正的整数。
you can change the order of the the conditions: 你可以改变条件的顺序:
if x.lower() == 'stop' or int(x) <=0
this way you check for 'stop'
first, and don't evaluated int(x)
(because the the or
condition already evaluates to True
). 这样你首先检查'stop'
,并且不评估int(x)
(因为or
条件已经计算为True
)。 any string that is not an integer and not 'stop'
would cause the ValueError
exception which you're already handling. 任何非整数而不是'stop'
字符串都会导致您正在处理的ValueError
异常。
You get a ValueError
because you can't convert the string 'stop'
to an integer. 您得到一个ValueError
因为您无法将字符串'stop'
转换为整数。
One way to solve this would be to use a helper method that correctly catches the ValueError
and then checks if the string is 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.