简体   繁体   English

逻辑门:x!= Python中的'减号'或'加号'

[英]logic gate: x != 'minus' or 'plus' in python

I've got a strange syntactical situation going on in an if...then statement. 在if ... then语句中,我遇到了一种奇怪的语法情况。 Not really sure what the fix is... 不太确定解决方案是什么...

x1 = 'minus'
if x1 == 'minus':
    print('OK')
if x1 != 'minus':
    print('this should not print')

y = {'direction':'minus'}
x2 = y['direction']
if x2 != 'plus' or x2 != 'minus':
    print("huh...")
if x1 != 'plus' or x1 != 'minus':
    print("??")
if x1 == 'plus' or x1 == 'minus':
    print("wait...")
print(x2)
if (x2 != 'plus') or (x2 != 'minus'):
    print("it wasn't the parenthesis...")

print(x2 != 'plus')
print(x2 != 'minus')

print(x2)

Output is: 输出为:

>OK
>huh...
>??
>wait...
>it wasn't the parethesis...
>True
>False
>minus

How do I create a logic gate in python that will only trigger if x != 'minus' or 'plus' in python? 如何在python中创建仅在x != 'minus' or 'plus'时触发的逻辑门?

How do I create a logic gate in python that will only trigger if x != 'minus' or 'plus' in python? 如何在python中创建仅在x!='minus'或'plus'时触发的逻辑门?

x is always not equal to one of those (think about it: if it's plus , that test isn't true—but plus is not minus , so the other test is true), so using or as you have will always be true! x 始终不等于其中的一个(考虑一下:如果它是plus ,则该测试不正确-但是plus不等于minus ,因此另一个测试 true),因此使用or as you have将始终为真!

What you probably want is something like this: 您可能想要的是这样的东西:

if not (x == 'minus' or x == 'plus')

Applying De Morgan's Law, you could also use: 应用戴摩根定律,您还可以使用:

if x != 'minus' and x != 'plus'

You can also use the more Pythonic: 您还可以使用更多的Pythonic:

if x not in ('minus', 'plus')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM