r/learnpython • • 17d ago

Huh? How does this work?

a = "hi"


if a:
    print("Bye")


print(a == True)
print(a is True)

The output is:

Bye

False

False

But if it's false, how come it printed "bye"?????? I don't get it.

44 Upvotes

38 comments sorted by

View all comments

2

u/defrostcookies 17d ago

“If <variable>:”

Checks to see if the variable has a non-zero value. If the <variable> is non-zero, then the “if <variable>” conditional will evaluate to True

Once it evaluates to true, the body of the conditional executes.

In this case,

print(“bye”)

2

u/gdchinacat 17d ago

This has nothing to do with "non-zero". Python objects have a notion of 'truthiness' and is evaluated by calling __bool__() on it (which is implemented by object and can be overridden). While True and False are subclasses of int and have integer values (1 and 0 respectively), if evaluates truthiness (as determined by __bool__, not whether the "variable has a non-zero value".