Lessons · Python · what counts as true
What counts as true
Empty things are false. Anything with something in it is true.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
It is why 'if items:' reads so cleanly instead of 'if len(items) > 0:'. Once you know the rule, a lot of real code stops looking like magic.
How to think about it
Ask: am I checking whether this EXISTS, or whether it has CONTENT? They are different questions, and None is not the same as empty.
Worked example
items = []An empty list.
if items:Empty counts as false, so this block does not run.
print("has things")Skipped.print(bool("0"))True. Any text with characters in it is true, including the character zero.Your turn
Print "nothing here" when a list is empty.
items = []
if items:
print("nothing here")Solve one with the tests running
The trap
0 is false and "0" is true. So is "False". The rule is about emptiness, not about what the characters spell.
Practise what counts as true on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.