The Python Apprentice
上QQ阅读APP看书,第一时间看更新

if...elif...else

For multiple conditions you might be tempted to do something like this:

>>> if h > 50:
... print("Greater than 50")
... else:
... if h < 20:
... print("Less than 20")
... else:
... print("Between 20 and 50")
...
Between 20 and 50

Whenever you find yourself with an else-block containing a nested if  statement, like this, you should consider using Python's elif keyword which is a combined else-if.

As the Zen of Python reminds us, Flat is better than nested:

>>> if h > 50:
... print("Greater than 50")
... elif h < 20:
... print("Less than 20")
... else:
... print("Between 20 and 50")
...
Between 20 and 50

This version is altogether easier to read.