Time for action – deciding with the if statement

We can use the if statement in the following ways:

  1. Check whether a number is negative as follows:
    >>> if 42 < 0:
    ...     print('Negative')
    ... else:
    ...     print('Not negative')
    ...
    Not negative
    

    In the preceding example, Python decided that 42 is not negative. The else clause is optional. The comparison operators are equivalent to the ones in C++, Java, and similar languages.

  2. Python also has a chained branching logic compound statement for multiple tests similar to the switch statement in C++, Java, and other programming languages. Decide whether a number is negative, 0, or positive as follows:
    >>> a = -42
    >>> if a < 0:
    ...     print('Negative')
    ... elif a == 0:
    ...     print('Zero')
    ... else:
    ... print('Positive') ...

Get NumPy : Beginner's Guide - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.