An if statement is a structure for decision making in Python. Python can execute line(s) of code based on a condition (sometimes this is called conditional statement)

By default Python runs lines of code sequentially, first line 1, then line 2, then line 3 etcetera. By using an if statement you can change this.

Lines of code inside the code blocks must be indented with four spaces at all times (not tabs)

Related Course: Complete Python Programming Course & Exercises

If statement syntax

The most basic form of an if statement is:

if <expr>:
<code>

In this form:

  • <expr> is an expressions that is evaluated
  • <code> one or more lines of code. These must be indentend by four spaces.

  • if the <expr> yields True: the code is executed

  • If the <expr> yields False: the code is skipped

if statement

Example: Python if statement

The example below shows an if statement.

The user types x (an integer). Only if the value is greater than zero, it is shown.

x = int(input("Enter x: "))
if x > 0:
print(f"x is {x}")

An example run is shown below:

Enter x: 5
x is 5

If you type zero or lower, nothing is shown:

Enter x: 0

python if statement

Related Course: Complete Python Programming Course & Exercises

If else

The else keyword can be added to the if statement. The block of code after the else, is only executed if <expr> is False.

x = int(input("Enter x: "))
if x > 0:
print(f"x is {x}")
else:
print(f"x is -{x}")

Note lines of code are in the block of code, if they have four spaces in front of them.

if else

Related Course: Complete Python Programming Course & Exercises

elif clause

There’s also the elif clause. Short for else if. This lets you check multiple conditions one by one.

if <expr>:
<statements>
elif <expr>:
<statements>
elif <expr>:
<statements>

Any number can be added. The example shows the checking of multipe conditions:

>>> name = "Vivian"
>>> if name == "Alice":
... print("Hello Alice")
... elif name == "Xander":
... print("Hello Xander")
... elif name == "Karen":
... print("Hello Karen")
... else:
... print("Hi")
...
Hi
>>>

You can optionally add another else at the end. Only one line(s) of code will be executed, but which depends on the condition.

Comparison operators

Python if statements usually have one of the following operators:

  • > greater than
  • < smaller than
  • == equals
  • != is not
  • >= greater than or equal
  • <= smaller than or equal

For example,

The condition x > 100 means only “the value of x should be greater than 100”.

The condition x != 2 means “the value of x should not be two”.

The program below tests if the value of x is equal to four.

x = int(input("Tell X "))

if x == 4:
print('You guessed correctly!')

print('End of program.')

The program always prints ‘End of program’ (normal sequential execution).

The text ‘You guessed correctly!’ will only be printed if the variable x equals four.

Nested if statements

If statements can be within if statements. That structure is called a nested if.

As a general rule you should not do this more than two times, because it gets very confusing to read.

The syntax is:

if <expr>:
if <expr>:
<statement>
<statement>
<statement>

For example the if statement below:

if x > 0:
if y > 0:
print("Both x and y larger")

The nested statements should have 8 spaces, because they are within the second if statement.

python nested if statement

You can still use elif and else within a nested if.

if x > 0:
if y > 0:
print("Both x and y larger")
else:
print("Only x is larger")

One line if statements

Usually an if statements spans multiple lines likes so:

if <expr>:
<statement>
<statement>

But you can write an if statement on a single line:

if <expr>:<statement>

There can even be multiple statements, if you separate them by a semicolon.

if <expr>:<statement>;<statement>;<statement>

The example below shows the single line if statement:

>>> x = 3
>>> if x >= 3: print('x is three or larger')
...
x is three or larger
>>>

You can do single line if statements like that:

>>> x = 3
>>> "x is less than ten" if (x < 10) else "x is greater or equal to ten"

Another example:

>>> x = 2
>>> y = 2
>>> f"x divided by y is {(x/y)}" if (y > 0) else "divide by zero"

Related Course: Complete Python Programming Course & Exercises

Boolean operators

You can apply boolean operators to the condition. This way you can combine if statements.

if <expr> and <expr>:
<statements>

A boolean or is also possible:

if <expr> or <expr>:
<statements>

Python if multiple conditions

What if you want to have multiple conditions? One way to deal with that is if you can type a lot of if statements like so:

x = 8

if x < 5:
print('x smaller than 5')

if x >= 5 and x <= 10:
print('great choice')

if x > 10:
print('x is too big')

But this becomes spaghetti code, not easy to read and might get confusing quickly. What you want to do is use the elif and else keywords.

x = 8

if x < 5:
print('x smaller than 5')
elif x >= 5 and x <= 10:
print('great choice')
else:
print('x is too big')

These codes will do exactly the same, but the above version is preferred because of readability and maintainability.

Summary

  • Normal execution is line by line, also called sequential

  • If statements select which code to execute.

  • If statements are decision makers. Only execute code if condition is True.

  • the if statement is used when you need to execute code only if the condition is True

  • the else clause is used when you want to run code if one condition fails

  • the elif clause lets you specify other conditions

  • An if statement is a type of control structure. A control structure directs the order of execution, in this case you want to run code only if a condition is True.

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

Download exercises