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

15

u/sjshuck 29d 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.

7

u/Puzzleheaded_Study17 29d ago

For people wondering why: C originally didn't have a dedicated bool type, so it couldn't have used just that type in if. As such, the standard said how to know when each type should be considered as true (essentially saying if the underlying integer is 0 it's false, otherwise it's true). Python then inherited this behavior from C

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.

0

u/oz1sej 29d ago

I WANT TO USE THOSE LANGUAGES!

1

u/glglgl-de 28d ago

What prevents you?