IF ELSE AND IF ELIF ELSE STATEMENTS
The if else statement executes different suites, based on whether a condition is True or False:
In [2]: if grade >= 60:
...: print('Passed')
...: else:
...: print('Failed')
...:
Passed
You must delete those four spaces so that the else: suite correctly aligns under the i in if. The following code assigns 57 to the variable grade, then shows the if else statement again to demonstrate that only the else suite executes when the condition is False:
In [4]: if grade >= 60:
...: print('Passed')
...: else:
...: print('Failed')
...:
Failed
Use the up and down arrow keys to navigate backwards and forwards through the current interactive session’s snippets. Pressing Enter reexecutes the snippet that’s displayed. Let’s set grade to 99, press the up arrow key twice to recall the code from snippet [4], then press Enter to reexecute that code as snippet [6]. Every recalled snippet that you execute gets a new ID:
In [6]: if grade >= 60:
...: print('Passed')
...: else:
...: print('Failed')
...:
Passed
Conditional Expressions
Sometimes the suites in an if else statement assign different values to a variable, based on a condition, as in:
In [8]: if grade >= 60:
...: result = 'Passed'
...: else:
...: result = 'Failed'
...:
We can then print or evaluate that variable:
Out[9]: 'Passed'
You can write statements like snippet [8] using a concise conditional expression:
In [11]: result
The parentheses are not required, but they make it clear that the statement assigns the conditional expression’s value to result. First, Python evaluates the condition grade >= 60:
- If it’s True, snippet [10] assigns to result the value of the expression to the left of if, namely 'Passed'. The else part does not execute.
- If it’s False, snippet [10] assigns to result the value of the expression to the right of else, namely 'Failed'.
In interactive mode, you also can evaluate the conditional expression directly, as in:
Out[12]: 'Passed'
Multiple Statements in a Suite
The following code shows two statements in the else suite of an if... else statement:
In [14]: if grade >= 60:
...: print('Passed')
...: else:
...: print('Failed')
...: print('You must take this course again')
...:
Failed
...: print('Passed')
...: else:
...: print('Failed')
...: print('You must take this course again')
...:
Passed
You must take this course again
if... elif... else Statement
You can test for many cases using the if... elif... else statement. The following code displays “A” for grades greater than or equal to 90, “B” for grades in the range 80–89, “C” for grades 70–79, “D” for grades 60–69 and “F” for all other grades. Only the action for the first True condition executes. Snippet [18] displays C, because grade is 77:
In [18]: if grade >= 90:
...: print('A')
...: elif grade >= 80:
...: print('B')
...: elif grade >= 70:
...: print('C')
...: elif grade >= 60:
...: print('D')
...: else:
...: print('F')
...:
C
The first condition—grade >= 90—is False, so print('A') is skipped. The second condition—grade >= 80—also is False, so print('B') is skipped. The third condition—grade >= 70—is True, so print('C') executes. Then all the remaining code in the if... elif... else statement is skipped. An if... elif... else is faster than separate if statements, because condition testing stops as soon as a condition is True.
else Is Optional
The else in the if... elif... else statement is optional. Including it enables you to handle values that do not satisfy any of the conditions. When an if... elif statement without an else tests a value that does not make any of its conditions True, the program does not execute any of the statement’s suites—the next statement in sequence after the if... elif... statement executes. If you specify the else, you must place it after the last elif; otherwise, a SyntaxError occurs.
Logic Errors
The incorrectly indented code segment in snippet [16] is an example of a nonfatal logic error. The code executes, but it produces incorrect results. For a fatal logic error in a script, an exception occurs (such as a ZeroDivisionError from an attempt to divide by 0), so Python displays a traceback, then terminates the script. A fatal error in interactive mode terminates only the current snippet—then IPython waits for your next input.