Wednesday, October 13, 2021

Inspired Python: Truthy and Falsy Gotchas

Truthy and Falsy Gotchas

Think back to when you wrote your first ever if statement in Python. I’m sure that intuition told you to only give Python boolean expressions that naturally evaluates to True or False, like 2 + 2 == 4.

But sooner, rather than later, you find yourself testing a list or a string’s length because it’s once again intuitive to you and, in other programming languages, possibly the only way to do so:

items = [1, 2]
if len(items) > 0 or items != []:
    print(f'There are {len(items)}')
else:
    print('There are no items')

Before long, however, you learn that it’s un-Pythonic: that there’s a better way, a shorter way. You learn that Python will evaluate just about anything in a boolean context given the opportunity and if you squint your eyes it all makes sense.



Read More ->

from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...