Understanding condition logic

后端 未结 2 588
一个人的身影
一个人的身影 2021-01-25 05:17

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 resu

相关标签:
2条回答
  • 2021-01-25 05:22

    Use any here:

    screens = ("workspace" , "screen" , "desktop" , "switch")
    threes = ("3" , "three", "third")
    
    if any(x in command for x in screens) and any(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.

    >>> False or []                     #all falsy values
    []
    >>> False or [] or {}               #all falsy values
    {}
    >>> False or [] or {} or 1          # all falsy values except 1
    1
    >>> "" or 0 or [] 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") in command and ("3" in command)
    

    help on any:

    >>> print any.__doc__
    any(iterable) -> bool
    
    Return True if bool(x) is True for any x in the iterable.
    If the iterable is empty, return False.
    >>> 
    
    0 讨论(0)
  • 2021-01-25 05:44

    "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" in command or "screen" in command or "desktop" in command or "switch" in command
    

    which is a verbose way to say what @Ashwini Chaudhary has used any for.

    0 讨论(0)
提交回复
热议问题