The IF statement in Python

Perhaps the best known type of statement in python is the if statement. Here are some examples of its application:

ยป More Python Examples

# geekole.com
i = 0
if i < 5:
    print('i is less than 5')

When executing the code we get this result:

IF statement in Python

This is the most basic form of the if statement in Python.

However, there are other variants such as if-else.

# geekole.com
i = 6
if i < 5:
    print('i is less than 5')
else:
    print('i is greater than 5')

The code below else will be executed if the condition tests false. Running this code we get the following:

IF statement in Python

Finally, we can combine if-else with other ifs. As in the following example:

# geekole.com
i = 5
if i < 5:
    print('i is less than 5')
elif i == 5:
    print('i is equal than 5')
else:
    print('i is greater than 5')

When you run the code, you will get the following:

IF statement in Python

Note: The screenshots in these examples are edited and run on the Visual Studio Code.

We hope this examples will be useful for you.