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')
    ...
    Negative
    

    This time, Python decided that 42 is negative.

What just happened?

We learned how to do branching logic in Python.

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

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