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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset