Choosing Which Statements to Execute
An if statement lets you change how your program behaves based on a condition. The general form of an if statement is as follows:
| | if condition: |
| | block |
The condition is an expression, such as color != “neon green” or x < y. (Note that this doesn’t have to be a Boolean expression. As we discussed in Using Numbers and Strings with Boolean Operators, non-Boolean values are treated as True or False when required.)
As with function bodies, the block of statements inside an if must be indented. As a reminder, the standard indentation for Python is four spaces.
If the condition is true, the statements in the block are executed; otherwise, they are not. As with functions, the block of statements must be ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access