IF STATEMENT
Let’s execute a Python if statement:
In [2]: if grade >= 60:
...: print('Passed')
...:
Passed
The condition grade >= 60 is True, so the indented print statement in the if’s suite displays 'Passed'.
Suite Indentation
Indenting a suite is required; otherwise, an IndentationError syntax error occurs:
...: print('Passed') # statement is not indented properly
File "<ipython-input-3-f42783904220>", line 2
print('Passed') # statement is not indented properly
IndentationError: expected an indented block
An IndentationError also occurs if you have more than one statement in a suite and those statements do not have the same indentation:
...: print('Passed') # indented 4 spaces
...: print('Good job!) # incorrectly indented only two spaces
File <ipython-input-4-8c0d75c127bf>, line 3
print('Good job!) # incorrectly indented only two spaces
^
IndentationError: unindent does not match any outer indentation level
Sometimes error messages may not be clear. The fact that Python calls attention to the line is usually enough for you to figure out what’s wrong. Apply indentation conventions uniformly throughout your code—programs that are not uniformly indented are hard to read.
Every Expression Can Be Interpreted as Either True or False
You can base decisions on any expression. A nonzero value is True. Zero is False:
...: print('Nonzero values are true, so this will print')
...:
Nonzero values are true, so this will print
In [6]: if 0:
...: print('Zero is false, so this will not print')
In [7]:
Strings containing characters are True and empty strings ('', "" or """""") are False.
Confusing == and =
Using the equality operator == instead of = in an assignment statement can lead to subtle problems. For example, in this session, snippet [1] defined grade with the assignment:
grade = 85
If instead we accidentally wrote:
grade == 85
then grade would be undefined and we’d get a NameError. If grade had been defined before the preceding statement, then grade == 85 would simply evaluate to True or False, and not perform an assignment. This is a logic error.