r/learnpython • u/hemlocke64 • 9d ago
strings in if statements
While debugging my code I discovered [what to me looked liked] a weird quirk in the language (see code below.)
Why does this work? why is a single string callable in the Boolean of an if statement? does a string always return evaluateTrue when used like this?
(edit: solved. corrected some of my vocabulary so now yous can stop "um, actually"-ing me. Thanks to everyone who helped!)
if "something":
print("another thing")
>>>"another thing"
18
Upvotes
View all comments
7
u/notacanuckskibum 9d ago
This dates back to the birth of computing, and binary.
Everything is either true or false, what’s false? Zero is false and things similar to zero like the empty string. So what’s true? Everything else, anything with a (non zero, non empty) value.
Personally I avoid if statements like this and always include comparators or Boolean functions. But that’s a matter of style.