I've got a strange syntactical situation going on in an if...then statement. 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?
How do I create a logic gate in python that will only trigger if x != 'minus' or 'plus' in python?
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!
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:
if x not in ('minus', 'plus')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.