r/learnpython • • 1d 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"
12 Upvotes

30 comments sorted by

40

u/favorite_stuff 1d 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.

4

u/Manostel-Jveive 18h ago

until someone passes the string `"False"` from a config file and wonders why the if block still runs

7

u/notacanuckskibum 1d 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.

7

u/drmonkeysee 1d ago edited 1d 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.

3

u/tomysshadow 1d 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

1

u/xenomachina xenomachina 17h 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.

Absolutely true.

I'd also argue that most languages that attempt to have strong typing (not to be confused with static typing) don't allow non-boolean values to be treated as boolean values. Python, for better or worse*, kind of mimicked C. C originally didn't have a boolean type, and instead treated non-0 as true, just like Python. Python took this idea, and then generalized it to other types.

C and Python both independently added boolean types eventually, but disallowing the automatic conversion at this point would be a very breaking change, and also extremely controversial as relying on it is even codified in PEP 8.

* personally, I wish Python hadn't done this, as I think it violates one of Python's own tenets: explicit is better than implicit.

4

u/Atmosck 1d 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.

13

u/PressF1ToContinue 1d ago

Google "python truthy".

6

u/EntrepreneurHuge5008 1d ago

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

Here's a brief explanation from GeeksforGeeks with some examples

3

u/TheBlackCat13 1d 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.

4

u/Atypicosaurus 1d 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 1d ago

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

1

u/TheRNGuy 1d ago

Implicit conversion to Boolean. 

1

u/SCD_minecraft 1d 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 1d ago

It isn't called it is evaluated.

0

u/Educational_Virus672 1d 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 1d 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 1d 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 1d 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.

0

u/bionicClown 1d ago

The best fix I could think of is don't use python. It stinks

-1

u/BabyLionCamel 1d ago edited 1d 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.

-3

u/roywill2 1d ago

Dont put that in your code, relying on obscure rules that arent clear. Either comment to explain how it works, or make it clear .... if len("something") > 0

4

u/CrambleSquash Flask, Pandas, Numpy 1d ago

This feature is very widely used. Perhaps it takes a little getting used to, but for me at least it's intuitive these days.

2

u/Orgasml 1d ago edited 1d 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 1d 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 1d ago

What is obscure about these rules?

0

u/[deleted] 1d ago

[deleted]

0

u/AlexMTBDude 1d 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 1d ago

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

0

u/Alternative-Emu2000 1d ago

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