Why does “if foo:” follow the branch even if the function foo returns False?

后端 未结 3 663
野趣味
野趣味 2021-01-29 00:14
def foo(a):
    print(\"I\'m foo\")
    return False


if foo:
    print(\"OK\")
else:
    print(\"KO\")

I run it and it returns OK. I know, I should h

相关标签:
3条回答
  • 2021-01-29 01:09

    python if condition statisfies if the value is not equal to any of these

    0, None, "", [], {}, False, ()
    

    Here

    def foo(a):
        print("I'm foo")
        return False
    
    >>>foo
    <function __main__.foo>
    

    That means variable foo pointing to the function.If you call your function foo(arg) then it will return False as you expecting.So

    >>>foo("arg")
    False
    
    0 讨论(0)
  • 2021-01-29 01:11

    When you write

     if foo:
        print("OK")
    else:
        print("KO")
    

    you are actually testing if the function pointer foo. It is defined, so it prints "OK" and it does not call the function. With the parenthesis, you call the foo function and runs its code.

    0 讨论(0)
  • 2021-01-29 01:15

    In this case your code is same as

    if foo != None:
        print("OK")
    else:
        print("KO")
    

    Result is

    "OK"

    because foo actually exists.

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