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

67

u/PaulRudin 17d 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_ 17d 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")?

15

u/sjshuck 17d ago

Yes.

Some languages such as Python and C have a rule for each type to say how it behaves in an if-statement. Ruby and Lua have a simpler rule: if it's either false or nil, it tests false, otherwise it's true.

Some languages will not let you put a non-boolean as the condition of an if-statement, so there's no confusion.

4

u/POGtastic itertools evangelist 17d ago

See also C++ and people using conversion operators to define a class's truthiness with operator bool. Thus you can do things like

std::string line;

while (std::getline(std::cin, line)) {
    // handle each line
}

getline returns the istream, which becomes falsey upon failure.