Understanding Condition Logic
I'm writing a python program that takes a given sentence in plan English and extracts some commands from it. It's very simple right now, but I was getting some unexpected results f
Solution 1:
Use any
here:
screens = ("workspace" , "screen" , "desktop" , "switch")
threes = ("3" , "three", "third")
if any(x in command for x in screens) andany(x in command for x in threes):
os.system("xdotool key ctrl+alt+3")
result=True
Boolean or
:
x or y
is equal to : if x is false, then y, else x
In simple words: in a chain of or
conditions the first True
value is selected, if all were False
then the last one is selected.
>>>Falseor [] #all falsy values
[]
>>>Falseor [] or {} #all falsy values
{}
>>>Falseor [] or {} or1# all falsy values except 1
1
>>>""or0or [] or"foo"or"bar"# "foo" and "bar" are True values
'foo
As an non-empty string is True in python, so your conditions are equivalent to:
("workspace") incommand and ("3"incommand)
help on any
:
>>> print any.__doc__
any(iterable) -> boolReturnTrueifbool(x) is Truefor any x in the iterable.
If the iterable is empty, returnFalse.
>>>
Solution 2:
"workspace" or "screen" or "desktop" or "switch"
is an expression, which always evaluate to "workspace"
.
Python's object has truth value. 0
, False
, []
and ''
are false, for example. the result of an or
expression is the first expression that evaluates to true. "workspace" is "true" in this sense: it is not the empty string.
you probably meant:
"workspace"incommand or "screen"incommand or "desktop"incommand or "switch"incommand
which is a verbose way to say what @Ashwini Chaudhary has used any
for.
Post a Comment for "Understanding Condition Logic"