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

后端 未结 3 723
野趣味
野趣味 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: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.

提交回复
热议问题