我希望可以选择退出或接受特定范围的值
I want to have the option to quit or accept specific range of values
q = input ("enter(1-51) or (q to quit):")
while q != 'q' and int (q) < 1 or int (q) > 51:
q = input ("enter(1-51) or (q to quit):")
我得到了下面的错误,我也尝试在变量周围使用 str()
也得到了同样的错误,还告诉我如何执行退出游戏或在游戏中使用的回合的技术如果这不是最好的方法,则类似于上面的内容。
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'q'
你的程序几乎是正确的。这是修复:
while q != 'q' and (int (q) < 1 or int (q) > 51):
通常,and
的优先级高于 or
。所以你的原始代码会被解释为:
while (q != 'q' and int (q) < 1) or int (q) > 51:
但是这种解释会导致错误的行为。因为如果 q == 'q'
,则 !=
为假,and
子句为假,所以 or
之后的第三个子句被计算。这会导致计算 int(q)
,从而导致异常。
非常简单的修复:添加方括号:
q = input ("enter(1-51) or (q to quit):")
while q != 'q' and (int (q) < 1 or int (q) > 51):
# brackets here ^ and here ^
q = input ("enter(1-51) or (q to quit):")
如果第一个条件为 False,如果没有括号,它总是会尝试 or int (q) > 51
。 (所以当 q == 'q'
时)但是有了括号,当 q == 'q'
时它不会进一步计算,所以你不必担心引发错误。另一方面,您仍然没有受到其他无效输入的保护:
enter(1-51) or (q to quit):hello
Traceback (most recent call last):
File "/Users/Tadhg/Documents/codes/test.py", line 2, in <module>
while q != 'q' and (int (q) < 1 or int (q) > 51):
ValueError: invalid literal for int() with base 10: 'hello'
因此您还可以在 int
转换之前添加另一个检查以确保所有字符也是数字 (.isdigit()
):
while q !='q' and not (q.isdigit() and 1<=int(q)<=51):
q = input ("enter(1-51) or (q to quit):")
while q != 'q' and int (q) < 1 or int (q) > 51:
q = input ("enter(1-51) or (q to quit):")
我得到了下面的错误,我也尝试在变量周围使用 str()
也得到了同样的错误,还告诉我如何执行退出游戏或在游戏中使用的回合的技术如果这不是最好的方法,则类似于上面的内容。
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'q'
你的程序几乎是正确的。这是修复:
while q != 'q' and (int (q) < 1 or int (q) > 51):
通常,and
的优先级高于 or
。所以你的原始代码会被解释为:
while (q != 'q' and int (q) < 1) or int (q) > 51:
但是这种解释会导致错误的行为。因为如果 q == 'q'
,则 !=
为假,and
子句为假,所以 or
之后的第三个子句被计算。这会导致计算 int(q)
,从而导致异常。
非常简单的修复:添加方括号:
q = input ("enter(1-51) or (q to quit):")
while q != 'q' and (int (q) < 1 or int (q) > 51):
# brackets here ^ and here ^
q = input ("enter(1-51) or (q to quit):")
如果第一个条件为 False,如果没有括号,它总是会尝试 or int (q) > 51
。 (所以当 q == 'q'
时)但是有了括号,当 q == 'q'
时它不会进一步计算,所以你不必担心引发错误。另一方面,您仍然没有受到其他无效输入的保护:
enter(1-51) or (q to quit):hello
Traceback (most recent call last):
File "/Users/Tadhg/Documents/codes/test.py", line 2, in <module>
while q != 'q' and (int (q) < 1 or int (q) > 51):
ValueError: invalid literal for int() with base 10: 'hello'
因此您还可以在 int
转换之前添加另一个检查以确保所有字符也是数字 (.isdigit()
):
while q !='q' and not (q.isdigit() and 1<=int(q)<=51):