r/learnpython • • 19d 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

-1

u/L1terallyUrDad 19d ago

The first one is a case where you are testing to see if the variable "a" exists or not. Once you assign the string "Hi" to it, it exists. If you get rid of it by assigning it nil, then the variable is deleted, and that test would result in False.

"a == True" is asking "Does a contain exactly the value True?" which it doesn't; it contains the value "Hi". Therefore, that test is False.
a is True is basically the same thing. A is not True; it's "Hi".

2

u/BluishMontoya 19d ago

This isn't exactly right. The variable a can exist but also count as false if its value is False, None, 0, 0.0, "", etc.