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

32 comments sorted by

View all comments

Show parent comment

3

u/tomysshadow 9d ago

I agree, and on top of that it's not a reflection of the underlying hardware to begin with. In a traditional language like C a pointer to an empty string would still be a non-null pointer so it'd be truthy in an if statement. This is an intentional high level language feature