r/learnpython • • 9h 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"
9 Upvotes

22 comments sorted by

28

u/favorite_stuff 9h ago

Every string is truthy except an empty string. Every list is truthy except an empty list. Every number is truthy except zero.

This is very convenient for while loops and x or y expressions, once you're used to it.

5

u/notacanuckskibum 7h ago

This dates back to the birth of computing, and binary.

Everything is either true or false, what’s false? Zero is false and things similar to zero like the empty string. So what’s true? Everything else, anything with a (non zero, non empty) value.

Personally I avoid if statements like this and always include comparators or Boolean functions. But that’s a matter of style.

3

u/drmonkeysee 4h ago edited 4h 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 to false if you wanted your coworkers to hate you.

1

u/tomysshadow 3h 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

12

u/PressF1ToContinue 9h ago

Google "python truthy".

3

u/Atmosck 8h ago

Python objects have a concept of being "truthy" or "falsy". Typically "truthy" means non-trivial, like for strings an empty string "" is falsy and other strings are truthy. It's basically a concise way to check if something exists.

5

u/EntrepreneurHuge5008 9h ago

Not callable, the if statement evaluates truthiness, not strict True/False values.

Here's a brief explanation from GeeksforGeeks with some examples

4

u/Atypicosaurus 8h ago

Try the following too

Empty string
if "":

A numeric value
if 346:

A numeric value of zero:
if 0:

A list
if [5, "foo"]:

An empty list
if [ ]:

2

u/pachura3 7h ago

You're a beginner, so you should never assume you have discovered a weird quirk or a bug in Python.

1

u/TheBlackCat13 4h ago

Note that python didn't even have True or False at all until python 2.2.1/2.3.0. Before that everything relied on truthiness.

1

u/TheRNGuy 8h ago

Implicit conversion to Boolean. 

1

u/SCD_minecraft 7h ago

Python does implicit casts to bools via .__bool__(self) method when needed

As rule of thumb - non empty collections (including strings) are True
None is False
Rest is more less True

If .__bool__ isn't defined, it deafults to True (representing "yes, object exists")

1

u/SaltCusp 7h ago

It isn't called it is evaluated.

0

u/Educational_Virus672 9h ago

it is called truthiness of a string i understood this concept as "" being 0 because it has 0 letters while others have more then 0 and 0 mean false while not 0 means true same wih int and list a empy or 0 is false while anything in list or any int that is not 0 is true

-1

u/LayotFctor 9h ago

Lot's of things work for reasons you don't expect, usually for legacy or simplicity reasons. Python gives you the ability to do it, because it's not there to tell you what you can or can't do. But if you don't think it makes sense, you should avoid it.

0

u/ontheroadtonull 9h ago

Try this in IDLE or a debug console:

bool("something") #check the boolean of a string

bool("") #check the boolean of an empty string.

Try bool(["something"]) and bool([]) as well to check a list and an empty list.

0

u/SharkSymphony 7h ago

One note: this implicit conversion to boolean (which you can do outside of an if statement too, by using bool()) is something different languages tend to do a little differently.

Also note: this is often exactly what you want, but it can also be a subtle source of bugs. Let's say that `if` statement guards something you want to do to a string input `val`. If "" is actually a valid input you want to do something with, then you'll need to figure out something else that can be the "no input" value and check for it explicitly. Typically that's None, in which case you'd modify the `if` clause to `if val is not None` instead.

-1

u/BabyLionCamel 9h ago edited 9h 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.

0

u/[deleted] 9h ago

[deleted] — view deleted comment

0

u/AlexMTBDude 9h ago

Strings don't return anything, only functions return something. A non-empty string evaluates to True while an empty string evaluates to False.

0

u/Chorizo_n_eggs 9h ago

When strictly referring to Python, the use of return and evaluate are very different. Hardly being pedantic imo.

0

u/Alternative-Emu2000 8h ago

That doesn't justify the abusive DMs and referrals to suicide helplines by the pathetic twat who corrected me.