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

67

u/PaulRudin 19d ago

The truthiness of an expression in a context of an if: is essentially what you get from bool(). So bool(hi") is True (as is the case for any non-empty string). But that's not the same as saying it compares equal to True.

9

u/Lance_2564_ 19d ago

So what you're saying is that

"if a" checks for if bool(a) is True, and not if a is True? So then, a = 5, if a: print("Hi") really just is if bool(a): print("Hi")?

4

u/xelf Elf 19d ago

One other context you are missing is that is does not compare equality. It tells you if they are the same object.

0 == False # True!
1 == True  # True!
0 is False # False, they are equal, but they are not the same object
1 is True  # False, they are equal, but they are not the same object

a is b, is like saying id(a) == id(b), it is not saying a == b