Support Our Site

To ensure we can continue delivering content and maintaining a free platform for all users, we kindly request that you disable your adblocker. Your contribution greatly supports our site's growth and development.

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>:    <statement>

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 greaterb 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 = 5b = 4if(a>b):
    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")


Latest Articles

Latest from djangocentral

How to Use Subquery() in Django With Practical Examples

In the realm of web development, Django stands as a powerful and versatile framework for building robust applications. One of the key aspects of developing efficient and optimized web applications is handling database queries effectively. In this article…
Read more →

4 min read

DRF Serializer: Handling OrderedDict and Converting It to a Dictionary or JSON

In Django Rest Framework (DRF) tests, when you access, you might encounter an OrderedDict instead of a regular dictionary. This behavior is intentional and reflects the design of DRF's serialization process.Understanding the Problem The u…
Read more →

3 min read

Django Rest Framework CheetSheet: Mastering API Development

Django Rest Framework (DRF) is a powerful toolkit that makes building robust and scalable web APIs with Django a breeze. Whether you're a seasoned Django developer or a newcomer, having a comprehensive cheat sheet at your disposal can be a game-changer. …
Read more →

5 min read

How to Perform NOT Queries in Django ORM

In Django, performing NOT queries allows you to exclude certain records from the query results based on specific conditions. The NOT operator, represented by the tilde (~) when used in conjunction with the Django ORM's Q object, helps you construct compl…
Read more →

3 min read