Utilize True value in Python def function

Asked 2 years ago, Updated 2 years ago, 14 views

def a():
    return True

a()
if a==True:
    print()

It's a simple one, but if you do it like above, it doesn't work properly.

def a():
    return True

if a():
    print()

If you do the following, it works normally, but I understand that the second code works when the true value comes back, but why not in the first code?
I'd appreciate it if you could answer.

python

2022-09-20 21:49

2 Answers

I wonder why you think it should be.

Let's make another very simple function. Function that tells you if it's even

def Even (number): return %2 == 0

if even (2): print(2, "is even")

It's a function that you can write like this.

Take the factor and determine if the number that came to the factor is even.

In your opinion, it should be something like if even or == True, but it doesn't make sense to compare function names without a factor.

Because a function has to be given a factor to know the result of calculation within the function. A function without a factor is a rather unusual case of a function.


2022-09-20 21:49

def a():
    return True

a()
if a==True:
    print()

In , the value of the function called through a() is The problem seems to be that the variable a in ifa==True is not assigned.

If you try print(a) in the above state, you will not run the function, but <function at ??> will return the function stored in memory. That is, a is a function that is not a variable (True). To execute a function, you must add () after the function.

Solution: Correct a() in the third line to a = a()!

Why is the second code executed

def a():
    return True

if a():
    print()

if a(): did not receive the information of function a through a() but rather 'executed' the function immediately. If you said if a:, it would have been interpreted as if <function at ??>:. It's not False, so of course the print() will work, but it will work with other intentions...


2022-09-20 21:49

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.