if
…else
and if
…elif
…else
StatementsThe if
…else
statement performs different suites, based on whether a condition is True
or False
. The pseudocode below displays 'Passed' if the student’s grade is greater than or equal to 60; otherwise, it displays 'Failed':
If student’s grade is greater than or equal to 60
Display 'Passed'
Else
Display 'Failed'
In either case, the next pseudocode statement in sequence after the entire If…Else is “performed.” We indent both the If and Else suites, and by the same amount. Let’s create and initialize (that is, give a starting value to) the variable grade
, then show and execute the Python if
…else
statement for the preceding pseudocode:
In [1]: grade = 85
In [2]: if grade >= 60:
...: print('Passed')
...: else:
...: print('Failed')
...:
Passed
The condition above is True
, so the if
suite displays 'Passed'
. Note that when you press Enter after typing print('Passed')
, IPython indents the next line four spaces. 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 [3]: grade = 57
In [4]: if grade >= 60:
...: print('Passed')
...: else:
...: print('Failed')
...:
Failed
The up and down arrow keys navigate backwards and forwards through the current interactive session’s snippets. Pressing Enter re-executes 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 re-execute that code as snippet [6]
. Every recalled snippet that you execute gets a new ID:
In [5]: grade = 99
In [6]: if grade >= 60:
...: print('Passed')
...: else:
...: print('Failed')
...:
Passed
if
…else
Statement FlowchartThe flowchart below shows the preceding if
…else
statement’s flow of control:
Sometimes the suites in an if
…else
statement assign different values to a variable, based on a condition, as in:
In [7]: grade = 87
In [8]: if grade >= 60:
...: result = 'Passed'
...: else:
...: result = 'Failed'
...:
We can then print
or evaluate that variable:
In [9]: result
Out[9]: 'Passed'
You can write statements like snippet [8]
using a concise conditional expression:
In [10]: result = ('Passed' if grade >= 60 else 'Failed')
In [11]: result
Out[11]: 'Passed'
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:
In [12]: 'Passed' if grade >= 60 else 'Failed'
Out[12]: 'Passed'
The following code shows two statements in the else
suite of an if
…else
statement:
In [13]: grade = 49
In [14]: if grade >= 60:
...: print('Passed')
...: else:
...: print('Failed')
...: print('You must take this course again')
...:
Failed
You must take this course again
In this case, grade
is less than 60
, so both statements in the else
’s suite execute. If you do not indent the second print
, then it’s not in the else
’s suite. So, that statement always executes, creating strange incorrect output:
In [15]: grade = 100
In [16]: if grade >= 60:
...: print('Passed')
...: else:
...: print('Failed')
...: print('You must take this course again')
...:
Passed
You must take this course again
if
…elif
…else
StatementYou can test for many cases using the if…elif…else
statement. The following pseudocode 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:
If student’s grade is greater than or equal to 90
Display “A”
Else If student’s grade is greater than or equal to 80
Display “B”
Else If student’s grade is greater than or equal to 70
Display “C”
Else If student’s grade is greater than or equal to 60
Display “D”
Else
Display “F”
Only the action for the first True
condition executes. Let’s show and execute the Python code for the preceding pseudocode. The pseudocode Else If is written with the keyword elif
. Snippet [18]
displays C
, because grade
is 77
:
In [17]: grade = 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
.
if
…elif
…else
Statement FlowchartThe following flowchart shows the general flow through an if
…elif
…else
statement. It shows that, after any suite executes, control immediately exits the statement. The words to the left are not part of the flowchart. We added them to show how the flowchart corresponds to the equivalent Python code.
else
Is OptionalThe 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.
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.
(True/False) A fatal logic error causes a script to produce incorrect results, then continue executing.
Answer: False. A fatal logic error causes a script to terminate.
(IPython Session) Show that a SyntaxError
occurs if an if
…elif
statement specifies an else
before the last elif
.
Answer:
In [1]: grade = 80
In [2]: if grade >= 90:
...: print('A')
...: else:
...: print('Not A or B')
...: elif grade >= 80:
File "<ipython-input-2-033bcba40157>", line 5
elif grade >= 80:
^
SyntaxError: invalid syntax