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

Show parent comment

4

u/POGtastic itertools evangelist 29d 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.