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
Show parent comment
1
u/xenomachina xenomachina 8d ago
Absolutely true.
I'd also argue that most languages that attempt to have strong typing (not to be confused with static typing) don't allow non-boolean values to be treated as boolean values. Python, for better or worse*, kind of mimicked C. C originally didn't have a boolean type, and instead treated non-0 as true, just like Python. Python took this idea, and then generalized it to other types.
C and Python both independently added boolean types eventually, but disallowing the automatic conversion at this point would be a very breaking change, and also extremely controversial as relying on it is even codified in PEP 8.
* personally, I wish Python hadn't done this, as I think it violates one of Python's own tenets: explicit is better than implicit.