我的目标:允许用户仅输入0或1(总共4个变量)。如果用户输入例如2,1,1,0,则应该抛出错误Only 0 and 1 allowed
。
到目前为止我尝试过的事情:
if (firstBinary != 0 or firstBinary != 1 and secondBinary != 0
or secondBinary != 1 and thirdBinary != 0 or thirdBinary != 1
and forthBinary != 0 or forthBinary != 1):
print('Only 0 and 1 allowed')
else:
print('binary to base 10: result)
问题:当我使用这样的陈述时,即使我输入例如5,我也得到结果,或者我得到的只有0和1允许'即使我写了全部1或0。
我发现这似乎是我追求的,但它仍然没有像我想要的那样工作:
if 0 in {firstBinary, secondBinary, thirdBinary, forthBinary} or 1 in \
{firstBinary, secondBinary, thirdBinary, forthBinary}:
print("Your result for binary to Base 10: ", allBinaries)
else:
print('Only 0 and 1 allowed')
这段代码基本上给了我与第一个代码示例相同的结果。
答案 0 :(得分:6)
使用any
:
v1, v2, v3, v4 = 0, 1, 1, 2
if any(x not in [0, 1] for x in [v1, v2, v3, v4]):
print "bad"
当然,如果您使用列表,它看起来会更好
inputs = [1, 1, 0 , 2]
if any(x not in [0, 1] for x in inputs):
print "bad"
答案 1 :(得分:3)
这是由于python中的运算符优先级。 or
运算符的优先级高于and
运算符,列表如下所示:
or
and
not
!=
,==
(资料来源:https://docs.python.org/3/reference/expressions.html#operator-precedence)
因此,python会像这样解释你的表达式(括号是为了澄清发生了什么):
if (firstBinary != 0 or (firstBinary != 1 and secondBinary != 0 or (secondBinary != 1 and \
thirdBinary != 0 or (thirdBinary != 1 and forthBinary != 0 or (forthBinary != 1)))))
导致与您想要的逻辑不同。有两种可能的解决方案,第一种是添加括号以使表达式明确。这是相当乏味和冗长的:
if ((firstBinary != 0 or firstBinary != 1) and (secondBinary != 0 or secondBinary != 1) and \
(thirdBinary != 0 or thirdBinary != 1) and (forthBinary != 0 or forthBinary != 1))
另一种方法是使用内置的all
函数:
vars = [firstBinary, secondBinary, thirdBinary, fourthBinary]
if not all(0 <= x <= 1 for x in vars):
print("Only 0 or 1 allowed")
答案 2 :(得分:1)
我将其细分为您试图解决的两个部分:
特定的输入是否有效? 所有输入的部分是否都有效?
>>> okay = [0,1,1,0]
>>> bad = [0,1,2,3]
>>> def validateBit(b):
... return b in (0, 1)
>>> def checkInput(vals):
... return all(validateBit(b) for b in vals)
...
>>> checkInput(okay)
True
>>> checkInput(bad)
False
>>>
答案 3 :(得分:0)
values = [firstBinary, secondBinary, thirdBinary]
if set(values) - set([0, 1]):
print "Only 0 or 1, please"