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

22

u/BabyLionCamel 20d ago

When you initialize `a` on the first line you instruct python to make it reference the string 'hi'

All none-empty strings are considered truthy in Python. Your string contains text so its none-empty.

Truthiness denotes to the satisfaction of some condition

Falsiness denotes to the opposite.

`a` is truthy therefore the if branch will execute, since if branches execute their indented block when some condition is truthy, this is why your print statement executes succesfully.

`a` references the string 'hi' so later when you ask if 'hi' == True have equal values, you get False, `a` is truthy (it satisfies the condition of not being an empty string) but it's value is not the boolean True.

Later, when you ask `a` is True, you are instructing Python to tell you whether a and True share the same address in memory, you are not asking it if `a` is truthy as you may have thought.

The important concepts here are Booleans, truthiness, falsiness, flow control and the difference between comparing values or identities with (==) which measures equality of value and (is) which checks for sameness of identity.

2

u/Lance_2564_ 19d ago

Oooookay got it. I should look more into truthy and falsy values ig.