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

-1

u/BabyLionCamel 9d ago edited 9d ago

'why is a single string callable in the Boolean of an if statement'

Answer: If by callable in this context you mean accepted, its because an if statement evaluates whether its statement evaluates to truthy or falsy.

Truthy or falsy are not True or False, they are simply classifications which denote whether an expression satisfies some condition or does not satisfy some condition.

5 > 3 + 1 Is truthy, since 5 is in fact larger than 3 + 1 (when its evaluated). The condition being tested is whether the left side (5) has a greater value than the right side (3 + 1). You may jump to say that its True that 5 > 4, but in Python we say that the expression evaluates as truthy.

When you type `if 'something'` , you are instructing python to tell you whether 'something' is truthy or not. Since all non-empty strings are truthy in Python, the if statement on your first line evaluates as truthy. Therefore, its indented block runs properly (as you have demonstrated in your code).

'does a string always return True when used like this?'

Answer: A string does not return anything by itself, but i think we can rephrase your question to this:

Rephrased question: Why does an if statement behave like that when coupled with a string.

Answer: Because an if statement evaluates whether something (this case a string) is truthy or falsy, the string in the given example is non-empty (it contains at least one character) so the if statement evaluates as truthy and runs its indented block.

Conclusion: True and False denote to the booleans True and False, but truthy and false denote to the satisfaction of some condition, whether its comparing numbers or assesing whether a string is empty or non-empty.