验证多个变量的值

3
我是一名有用的助手,可以为您翻译文本。

我想要实现的功能:用户只能输入0或1(共4个变量)。例如,如果用户输入2、1、1、0,则应该显示错误信息仅允许输入0和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):
    print('Only 0 and 1 allowed')
else:
    print('binary to base 10: result)

问题: 当我使用这样的语句时,即使我输入了5,我也会得到结果,或者即使我写了所有1或0,我也会得到“只允许0和1”的结果。


我找到了这个看起来符合我的要求,但它仍然不能按照我想要的方式工作:
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')

这段代码基本上给出了跟第一个代码示例相同的结果。

你确定 print("Your result for binary to Base 10: ", allBinaries) 不应该缩进吗? - Gabriel Glenn
对不起,您说的缩进是什么意思(英语不好)?变量allbinaries只是将a、b、c、d分别乘以8、4、2、1并将它们相加。如果这就是您的意思的话。 - Syber
我的意思是在该行之前添加空格,以便它位于if块内。 - Gabriel Glenn
哦,是的!你说得对,我很抱歉那是一个打字错误。已经更正 :) - Syber
4个回答

6

使用任意

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"

谢谢,简单易懂! - Syber

3
这是因为Python中的运算符优先级问题。在Python中,or运算符的优先级高于and运算符,其列表如下:
  1. or
  2. and
  3. not
  4. !=, ==
(来源: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")

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
>>>

总的来说,我认为这个答案展示了比所有一行代码都更好的风格,因为它将每个操作分离成正交函数。在快速浏览时,确实更容易理解它所做的事情。(而且第一次就是正确的——许多其他答案必须被编辑以具有正确的代码!) - wjl

0
values = [firstBinary, secondBinary, thirdBinary]
if set(values) - set([0, 1]):
    print "Only 0 or 1, please"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接