DEV Community

Yehan Wasura
Yehan Wasura

Posted on • Originally published at Medium on

The Truth About Python’s Truthiness

Stop writing if name == 'java' or 'html' ; it’s not doing what you think it’s doing.

Within the first glance, it looks like a simple check that sees whether the variable name is either java or html. If you thought, so, then this article is mainly for you.

I found this while scrolling Instagram in a Saturday evening, there was a reel with a challenge similar to below code (sorry, I couldn’t find the original one, so this is my version of it). And looking at the comment section, there were many confused people — hence, this article.

name = 'python'
if name == 'java' or 'html':
    print('correct name')
else:
    print('wrong name')
Enter fullscreen mode Exit fullscreen mode

The output of the above code is correct name.

Now let’s analyze and see why?

Python is not interpreting this as two comparisons, so in your mind the above code should look like this:

(name == 'java') or (name == 'html')
Enter fullscreen mode Exit fullscreen mode

But Python actually parses it as:

(name == 'java') or ('html')
Enter fullscreen mode Exit fullscreen mode

You see the difference? html is a non-empty string and sitting alone there. The whole right side of the or operator is now a non-empty string.

To understand this, run the below code and observe the output:

x = ""
if x:
  print("Case 1")
else:
  print("Case 2")
Enter fullscreen mode Exit fullscreen mode

The output gives you Case 2 because, the IF-condition checks if the string is Empty or Not.

  • Empty String → False
  • Non-Empty String → True

Let’s get back to here : (name == 'java') or ('html')

or becomes the operator here that separates the code into left and right parts.

  • name == 'java' → returns False (because name was 'python')
  • 'html' → returns True (because it's non-empty string)

So the total expression is now look like this: False or True, which we all know with the basic logic gates knowledge is True (or-gate returns True as long as at least one output is True).

This happens because of the single string just sitting there, because Strings in python are considered “truthy”.

What in the world is Truthy?

Truthy ” is a term used in Python (and many other programming languages), and it refers to values that are considered True when evaluated in a *Boolean * context.

Make a note that, this is not the same as the Boolean value True.

When these truthy values are used in conditions like if-statements or while-loops , a truthy value will cause the condition to pass.

↓ Just a Fun Fact for Non-native English speakers me:

Other than in the Programming context, word “truthy” has an older, non-technical definition and a more modern common usage as well:

Older : it is used to simply mean truthful or veracious (telling the truth).

Modern Slag/ Colloquialism : The term was famuously popularized in 2005 by U.S. comedian Stephen Colbert. Where “truthiness” (noun) refers to the quality of seeming or being felt to be true, even if it not supported by facts or evidence. (i.e, gut feeling).

The adjective “truthy” is used to describe something that has that quality.

Truthy and Falsy in Python

This is one of those things that seems wrong until you look a bit deeper. In Python, Logical operators don’t force a boolean context unless they _have _to.

They operate on “objects”, not just True or False. In Python, every value has an inherent Boolean nature.

So:

expr1 or expr2
Enter fullscreen mode Exit fullscreen mode

Returns expr1 if it’s truthy, otherwise returns expr2. This is not about correctness or boolean purity. It’s all about evaluating the minimum necessary and then passing the original value up.

That is why this works:

username = input() or "guest"
Enter fullscreen mode Exit fullscreen mode

If you enter nothing, input() returns an empty string(falsy), so “guest” becomes the final value. Super convenient. But the moment you’re doing real comparisons, this same behavior becomes a gremlin waiting to ruin your code (at least in the pre-AI era… you lucky b — well, you get the idea).

Anyway, let's look at what objects are truthy and falsy in python, so you don’t get bamboozled again.

Falsy Values (Exceptions)

The concept of “truthy” is easiest to understand by first knowing the exceptions that are considered as falsy. These are the values that evaluate to False in a Boolean context.

  • The Boolean False itself.
  • Zero of any numeric type : ◗ Integer (int) : 0 ◗ Float (float): 0.0 ◗ Complex (complex ): 0j
  • Empty sequences and collections: ◗ Empty String: "" or '' ◗ Empty List: [] ◗ Empty Tuple: () ◗ Empty Dictionary: {} ◗ Empty Set: set()
  • The special value ** None**

Truthy Values (Everything Else)

Every value that is NOT one of the falsy values given above is considered truthy.

  • The Boolean True
  • Any non-zero number (positive or negative)
  • Any non-empty sequence or collection (__bool__ or __len__) that makes them falsy.

So, what is the right way to write our original intention?

Well in programming there are different ways to do things, because it all depends on the program you're building, here are some very common ways to do this particular thing.

Repeat the comparison  — if you actually wanted to check if name is 'java' or 'html’, you need to repeat the comparison.

if name == 'java' or name == 'html':
  ...
Enter fullscreen mode Exit fullscreen mode

Use in keyword  — cleaner way in my opinion, because it reads better and has zero ambiguity, also doesn’t rely on the truthiness magic.

if name in ('java', 'html'):
  ...
Enter fullscreen mode Exit fullscreen mode

Many other languages also support this truthiness/falseness concepts, but some of them do not allow them at all. Here is an extra breakdown of a few selected languages:

Languages where “truthiness / falsiness” is built in (non-boolean values allowed in conditionals)

  • JavaScript ◗ JS has a defined set of falsy values: false, 0, -0, 0n, "", null, undefined, NaN. Everything else is truthy — numbers (non-zero), non-empty strings, objects, arrays, functions, etc. ◗ Because of this, constructs like if (someString) or if (someObject) work, even if the value isn’t strictly true or false.
  • Ruby ◗ Ruby’s rule is simpler: only false and nil are falsy. Everything else — even 0, "", empty arrays — is truthy.
  • PHP ◗ "", "0", 0, 0.0, (), undef → falsy
  • Perl ◗ "", "0", 0, 0.0, (), undef → falsy
  • Lua ◗ only false and nil are falsy ◗ everything else → truthy
  • Shell Scripting (bash, sh) ◗ Commands return exit codes; ◗ 0 = truthy, non-zero = falsy (Completely reversed from typical languages.)

Languages where truthiness is not allowed or is very limited

  • Java ◗ if ("hello") → compile error ◗ Must use: if (someBooleanExpression)
  • C / C++ (modern style) ◗ C itself treats 0 as false and non-zero as true — but that’s not real “truthiness,” it’s integer coercion, not object truth value. ◗ Anything that’s not an integer must be explicitly converted. ◗ C++ (modern) is stricter: ◗ You cannot do: if (“abc”) // error in modern compilers
  • C# ◗ Very strict. if ("text") → compile error
  • Go ◗ Bans truthiness completely. ◗ You must write:if len(s) > 0 { … } ◗ You cannot do: if s { … } // error
  • Rust ◗ Same as Go, No truthiness. ◗ You must explicitly compare or convert. if my_vec.is_empty() { … }
  • Swift ◗ you cannot use arbitrary types in an if condition — the expression must evaluate to a Boolean type. For example, if [] { ... } or if 0 { ... } won’t compile.
  • TypeScript (in strict mode) ◗ JS has truthiness, but TypeScript tries hard to warn you.

What these language comparison tells us is that,

  • Not all “truthiness” rules are the same across languages. What counts as falsy in one might be truthy in another.
  • Even languages with truthiness may treat containers differently. For example, JS considers even empty arrays as [] as truthy.
  • Type coercion vs strict boolean types: Some languages like C treat (0 vs non-zero) as (false vs true), but that’s integer coercion, not truthiness in the modern sense.

Because of all these nuances and caveats, you can’t assume a universal “ truthiness rule ”, Always check the language spec or docs.

Truthiness isn’t a flaw — it’s one of Python’s most flexible features. But like anything powerful in programming, it can betray you if you don’t fully understand it.

As the quote goes:

‘Great power comes with great responsibilities.’


Top comments (0)