If Statements

2.2. If Statements#

The if statement lets us execute a section of code if a specified condition is True.

../../_images/1_example3.png

The structure of an if statement is:

if condition:
    # code you execute if condition is true

Take note of the following:

  • if is a keyword

  • The condition must evaluate to either True or False

  • The code inside the if statement only executes if the condition is True

  • : is placed at the end of the condition

  • The code inside the if statement must be indented. The indentation defines the code block. This allows you to put multiple lines inside the if statement.

  • The indentation can be done using tab or spaces, as long as you’re consistent!

Here is an example of a simple if statement.

x = -2

if x < 0:
    print('x is a negative number')
x is a negative number

In this example the condition is True so the print statement runs.

This is how we can represent this code diagrammatically. The green line indicates the ‘path’ the code takes.

../../_images/1_example2.png

Let’s look at another example.

x = 1

if x < 0:
    print('x is a negative number')

In this example the condition is False so the print statement does not run.

../../_images/1_example3.png