| Goals: |
|
Chapter 4 introduced Excel’s command. In this section, we will introduce the equivalent if command in Python, which is, from a visual standpoint, more friendly to read and construct.
First, however, we must introduce another data type: boolean. Unlike number-types or strings, boolean has only two possible values: True or False. In Python, there are certain comparisons that will evaluate to True or False. The following table gives those we will use:
Figure 5.15 shows two Shell windows with examples:
In the following, let and denote a boolean values, i.e., something that evaluates to True or False. Here’s how the if statement works:
Notes:
The else part is optional, i.e., a standalone if is okay.
The elif part may also be optional, given the scenario.
As with the def command, the colon : denotes the beginning of the group of command(s) to execute. If one forgets the colon, IDLE won’t auto-indent and the Shell will give a syntax error. And, as with the def examples prior, grouping is done by indenting in multiples of 4; any other number of indentations will cause a syntax error.
Some examples:
Answer the following as True or False.
There is no difference between = and ==.
The syntax >< is used to denote not equal to.
Boolean values consist of only True, False, or Maybe.
Indentation is necessary for if statements.
The else part is required in all if statements.
Write a function that takes as input a number and outputs the following: if is greater than 5, return 9; otherwise return 3.
Write a function that uses randbetween to randomly generate an integer between 0 and 2, inclusive. The function returns ”Yes” if is equal to 0, ”No” if is 1, and ”Maybe” otherwise.