Andreas Bergström

Full Stack Web Developer

Python Tips and Gotchas #4 - Understand truthy and falsy

2019-04-04 - 255 words - 2 minutes to read

Truthy and falsy are the ways values implicitly converts to booleans when used in if-expressions, and are different to the booleans True and False. Booleans work pretty much identical in every major programming language. But the workings of truthy and falsy are not. Javascript are infamous for being really messy and inconsistent with its truthy and falsy values, while Swift and C# simply does not allow any implicit conversion to booleans. Python sits somewhere in between with a very rational and sensible arrangement.

When evaluated in if-expressions, the following values will evaluate to False:

New Python developers with a background in Javascript or PHP should note that there is no such thing as loosely comparissons in Python. So while you in Javascript can do this:

1
2
3
4
> '' == false
true
> '' === false
false

And in PHP:

1
2
3
4
php > if('' == false) { echo 'false';  }
false
php > if('' === false) { echo 'false';  }
php > 

But Python does not work the same way, there is only strict comparisson that compares both value and type:

1
2
3
4
>>> '' == False
False
>>> '' == True
False
comments powered by Disqus