How To Write Conditional Statements In Python

3 min read

In programming, oftentimes we want to execute a particular block of code only, and we might need to skip over some lines too. Conditional statements can help us to do so. Conditional Statements give us greater control over our program.

With conditional statements, we can make a block of code run or skip over depending upon the condition we provide.

Conditional expressions, involving keywords such as if, elif, and else, provide Python programs ability to perform different actions depending on a boolean condition: True or False.

This article, we will take you through writing conditional statements in Python.

If statement in Python

if <expression>:

An if statement starts with if keyword which should always be written in lowercase followed by an expression. If the expression returns a True value then the statement below the if statement will get executed and if it returns False then the interpreter will skip over this part.

Let's look at a simple number comparison example;

 >>> a = 5

>>> b = 4

>>> if(a>b):
...     print(" a is greater")
 a is greater

The syntax is very specific therefore you must pay close attention to the layout.

The if keyword must end with a colon(:) and the statements below the if condition should always be indented. Python relies on indentation to know which lines or block of code is contained under the if condition.

Always indent the statement by adding 4 spaces to the right of the statement.

If you don't indent your code, you will get an error ;

 >>> if(a>b):
... print( a is greater")

    print("a is greater")
IndentationError: expected an indented block

One line if statements in Python

We can also limit the if statement to one line like this,

 >>> if(a>b): print("a is greater")

a is greater

We can add multiple statements by separating them with a semicolon (;)

 >>> if(a>b): print("a is greater") ; print("b is smaller")

a is greater
b is smaller

Although it works as expected, it is advisable to spread the program in multiple lines to increase the reliability.

Else Statement In Python

It is likely that we will like our program to do something else even when if statement evaluates to false. The else keyword lets us do that.  These could be understood by the following control flow chart.

if a certain condition is true:

       then the following actions must be performed;


       these actions must be performed

By combining else and if statement we are constructing a two-part conditional statement, which tells the Python interpreter to run the block of codes depending upon the conditions.

Let's go back to our previous example and modify it,

>>> a = 5
>>> b = 4

 >>> if(b>a):
...     print(" b is greater")
... else:
...    print("a is greater")
a is greater

In the above example, if statement evaluates to false therefore else statement got executed.

Similar to if, else keyword should always end with a colon(:) and the statement inside it should be indented.

Else if statement In Python

There might be a possibility of having more than 2 outputs in our program, and we want to perform condition operation for each output. This can be achieved by else if statement in Python.

The elif keyword is similar to the if statement which will evaluate another condition.

Let's again go back to our number comparison example where we might encounter a situation where both numbers are equal, using an elif statement can evaluate this condition.

>>> a = 4
>>> b = 4

>>> if(a>b):
...    print("a is greater")

... elif(a==b):
...    print("Both the numbers are equal")

... else:
...     print("b is greater")

Both the numbers are equal

Now we have conditions for all possible outcomes of this program.

Nested If Statements in Python

Once you have a good grasp over the basic conditional statements, You can create more advance conditional statements.

When would you want to use nested if statements?

We should use nested if statements when we want to check a second condition if the first condition evaluates to True.

Now let's go back to our number comparison example again, this time we will add a nested if statement to check if the value of a is greater than 2 or not,

a = 5
b = 4

    if (a>2):
        print("a is greater than b and 2")
        print("a is greater than b but less than 2")
    print("b is greater")


author's image
Abhijeet Pal Author and Editor in Chief @djangocentral

Abhijeet is a full-stack software developer from India with a strong focus on backend and system design. He is driven by the need to create impactful solutions that add value to the internet in any way possible.

LinkedIn Twitter Github

Latest Articles

Latest from djangocentral

Django 4.1 adds async-compatible interface to QuerySet

The much-awaited pull request for an async-compatible interface to Queryset just got merged into the main branch of Django.Pull Request - The Django core team has been progressively adding async suppor…
Read more →

3 min read

Making Django Admin Jazzy With django-jazzmin

Django admin is undoubtedly one of the most useful apps of Django. Over the years there has been very little change in the admin app as far as the UX is concerned and it's not a bad thing at all. Django admin was designed to provide a simple and minimali…
Read more →

4 min read