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

2

u/Orgasml 9d ago edited 9d ago

It's not an obscure rule though. Empty strings in python are nontruthy. So if you did:

word = ""
if word: 
    print(word)
else:
    print("word is empty")

it will work as expected.

0

u/roywill2 9d ago

Well its obscure to me and a bit weird. Like those puzzles 2×3+4÷2 that depend on obscure precedence rules .... just put in the parentheses!

1

u/glglgl-de 9d ago

What is obscure about these rules?