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 ...

Get Practical Programming, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.