A program sometimes may have to make choices. These choices can execute different code depending on certain condition.

In Python the if statement is used for conditional execution or branching. An if statement is one of the control structures. (A control structure controls the flow of the program.)

The if statement may be combined with certain operator such as equality (==), greater than (>=), smaller than (<=) and not equal (!=). Conditions may be combined using the keywords or and and.

Related course: Complete Python Programming Course & Exercises

Introduction

In the example below we show the use if statement, a control structure. An if statement evaluates data (a condition) and makes a choice.

Lets have al look at a basic if statement. In its basic form it looks like this:

1
2
3
#!/usr/bin/env python3
if <condition>:
<statement>

In this form

  • is the condition evaluated as a Boolean, it can either be True or False.
  • is one more lines of code. Each of those lines must indented with four spaces.

Several examples of the if statements are shown below, you can run them in the Python interpreter:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/usr/bin/env python3
>>> x = 3
>>> if x < 10:
... print('x below ten')
...
x below ten
>>> if x > 10:
... print('x is greater than ten')
...
>>> if x > 1 and x < 4:
... print('x is in range')
...
x is in range
>>>

Itג€™s very important to have four spaces for the statements. Every if statement needs a colon.
More than one condition can be combined using the and keyword.

Indentation and Blocks

An if statement doesnג€™t need to have a single statement, it can have a block. A block is more than one statement.

The example below shows a code block with 3 statements (print). A block is seen by Python as a single entity, that means that if the condition is true, the whole block is executed (every statement).

1
2
3
4
5
6
#!/usr/bin/env python3
x = 4
if x < 5:
print("x is smaller than five")
print("this means it's not equal to five either")
print("x is an integer")

All programming languages can create blocks, but Python has a unique way of doing it. A block is defined only by its indention.

Other programming languages often used symbols like {, } or words begin and end.

So the basic form of a Python if statement block is:

1
2
3
4
5
6
if <condition>:
<statement>
<statement>
<statement>

<statement> # not in block

After completing the if statement, Python continues execution of the program. The if statement ends by its indetion, it goes back four spaces.

Visual example of if statement (click to enlarge):
if statement

If-Else

You can use if statements to make an interactive program. Copy the program below and run it.
It has several if statements, that are evaluated based on the keyboard input.

Because keyboard input is used, we use the equality sign (==) for string comparison.
The second string is typed, but we need a number. You can convert the string to an integer using int().

It also makes use of the else keyword, this is the other evaluation case. When comparing age (age < 5) the else means (>= 5), the opposite.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/usr/bin/env python3

gender = input("Gender? ")
gender = gender.lower()
if gender == "male":
print("Your cat is male")
elif gender == "female":
print("Your cat is female")
else:
print("Invalid input")

age = int(input("Age of your cat? "))
if age < 5:
print("Your cat is young.")
else:
print("Your cat is adult.")

Elif

If you want to evaluate several cases, you can use the elif clause. elif is short for else if. Unlike else with elif you can add an expression.
That way instead of writing if over and over again, you can evaluate all cases quickly.

1
2
3
4
5
6
7
8
9
10
11
12
>>> x = 3
>>> if x == 2:
... print('two')
... elif x == 3:
... print('three')
... elif x == 4:
... print('four')
... else:
... print('something else')
...
three
>>>

This is a more elegant and Pythonic than to write a list of if-statements as shown below.

1
2
3
4
5
6
7
x = 3
if x == 2:
print('two')
if x == 3:
print('three')
if x == 4:
print('four')

But comes down to the same thing, the only difference is the syntax (and readablity).

If you are a beginner, then I highly recommend this YouTube Python Playlist.

Exercise

Do these exercises:

1
2
3
4
1\. Make a program that asks the number between 1 and 10\. 
If the number is out of range the program should display "invalid number".

2\. Make a program that asks a password.

Once completed continue with the next exercise.