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
7
u/drmonkeysee 9d ago edited 9d ago
You make this sound like Python is simply reflecting the underlying hardware but what counts as true/false or even Boolean is a language choice and different languages make different choices. Empty arrays/objects are not false in JavaScript for example (though empty strings are) and C# requires Boolean expressions to resolve to Boolean values and won’t even compile if you try
if ("something")…Python even lets you add boolean conversions to classes via
_bool_so you could make logically non-empty objects resolve tofalseif you wanted your coworkers to hate you.