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