Skip to main content
Taught by Tech Leads

Master pipelines, cloud & AI to become an operational Data Engineer.

DataScientist.fr
Image de The conditions in Python: if, else, elif - Practical tutorial
Python

The conditions in Python: if, else, elif - Practical tutorial

Photo de Romain DE LA SOUCHÈRE

Tech Lead, CTO AXI Technologies

Published on 8 janvier 2025 · 10 min of reading

Introduction to conditional statements in Python

Conditional statements are an essential component of programming in Python. They allow developers to control the flow of their program by executing different sections of code based on specific conditions.

What is a conditional statement?

A conditional statement is a declaration that allows a program to choose between multiple possible execution paths. In Python, these statements are often introduced by the keywords if, else, and elif (short for 'else if').

Importance of conditional statements

Conditional statements are crucial because they enable programs to make decisions. For example, a program may check if a user is logged in before displaying their profile. Without these statements, programs would be linear and unable to react to different situations or input data.

Basic syntax

Here is a simple example of a conditional statement in Python:
python
In this example, the program checks if the variable age is greater than or equal to 18. If so, it displays 'You are an adult'. Otherwise, it displays 'You are a minor'.

Benefits

Conditional statements make code flexible and dynamic. They can be used to validate data, handle errors, or adapt the program's behavior based on user needs.
By understanding these basics, you will be better prepared to explore more advanced concepts like nested statements and conditional expressions.

The basics of If statements

To fully understand conditional statements in Python, it is essential to master the basics of if statements. These statements allow you to execute a block of code only if a given condition is true.

If statement syntax

The syntax of an if statement is simple:
python
The condition is an expression that returns True or False. If the condition is true (True), the indented block of code under the if statement is executed.

Basic example

Let's take a simple example:
python
Here, the program checks if the variable temperature is greater than 20. If so, it displays 'It's hot outside'.

Using multiple conditions

You can also combine multiple conditions using the logical operators and, or, and not:
python
In this example, both conditions must be true for the message to be displayed.

Importance of indentation

It is crucial to note that indentation in Python is mandatory and serves to delimit code blocks. Without correct indentation, your code will not function as expected.
By mastering these basics, you will be well prepared to explore more complex conditional statements like if else and if elif else.

Using If Else statements

After understanding the basics of if statements, it is time to look into using if else statements. These allow for handling situations where multiple conditions need to be checked and different actions need to be executed based on the cases.

If Else statement syntax

The syntax of an if else statement is as follows:
python

Practical example

Let's take a simple example to illustrate this:
python
In this example, the program checks if the variable grade is greater than or equal to 60. If so, it displays a congratulatory message. Otherwise, it displays a message encouraging review.

Handling alternative cases

The else statement is useful to ensure that a block of code will be executed even if the initial condition is not met. This allows for handling alternative cases in a clear and structured manner.
Using if else statements allows you to make your programs more interactive and responsive to the different situations you may encounter.

Introduction to If Elif Else statements

After mastering if and if else statements, it is important to understand if elif else statements, which allow for handling multiple conditions sequentially. The elif keyword means 'else if' and can be used to check another condition if the previous condition is false.

If Elif Else statement syntax

The basic syntax is as follows:
python

Practical example

Here is an example to illustrate the use of if elif else statements:
python
In this example, the program first checks if the variable grade is greater than or equal to 90. If not, it checks if it is greater than or equal to 75, then 60, and displays an appropriate message for each case.

Usefulness of If Elif Else statements

The if elif else statements allow you to handle multiple conditions clearly and concisely, making the code more readable and easier to maintain. They are particularly useful when you need to check multiple criteria and take different actions based on each criterion.
By mastering these techniques, you will be able to write more robust and flexible programs.

Understanding nested statements

Nested statements are conditional statements placed inside other conditional statements. They allow for managing more complex conditions by checking multiple levels of conditions.

Nested statements syntax

Here is how you can nest conditional statements:
python

Practical example

Let's take an example to illustrate this:
python
In this example, the program first checks if the user is an adult (age > 18). If so, it then checks if the income is sufficient (income > 30000). If either condition is not met, an appropriate message is displayed.

Benefits of nested statements

Using nested statements allows for managing scenarios where multiple levels of conditions need to be checked. They make the code more flexible and capable of handling complex situations.
However, it is important to use nested statements sparingly to avoid making the code too complex and difficult to read.

Simplifying your code with short statements

To make your code more readable and concise, Python offers ways to simplify conditional statements using short expressions, also known as ternary expressions.

Ternary expressions

Ternary expressions allow you to write simple conditions in a single line. The syntax is as follows:
python

Practical example

Here is an example to illustrate the use of a ternary expression:
python
In this example, the variable status will be set to 'adult' if age is greater than or equal to 18; otherwise, it will be set to 'minor'.

Benefits of ternary expressions

Ternary expressions help reduce the number of lines of code and improve readability when the conditions are simple. They are particularly useful for variable assignments based on a condition.

Using with functions

Ternary expressions can also be used in functions to return conditional values concisely:
python
By using these techniques, you can make your Python code simpler and more elegant while maintaining its functionality and clarity.

Summary and next steps for beginners

We have covered a wide range of concepts related to conditional statements in Python. Here is a summary of the main points and some suggestions for the next steps in your learning.

Summary

  1. If Statements: You have learned to use if statements to execute a block of code when a condition is true.
  2. If Else Statements: You have discovered how to handle alternative cases with the else statement.
  3. If Elif Else Statements: We explored how to check multiple conditions sequentially with elif.
  4. Nested Statements: You have seen how to nest conditional statements to manage more complex scenarios.
  5. Short Statements: You learned to use ternary expressions to simplify and condense your code.

Next Steps

To consolidate your knowledge and progress in Python programming, here are some suggestions:
  1. Practice: Write simple programs that use different combinations of conditional statements.
  2. Projects: Try creating small projects, such as a grading system or a tax calculator, to apply what you have learned.
  3. Code Reading: Examine the source code of open-source projects to see how other developers use conditional statements.
  4. Documentation: Refer to the official Python documentation to deepen your understanding of conditional statements and coding best practices.
By following these steps, you will be well prepared to tackle more advanced programming concepts and improve your Python skills.

Want to go further?

This topic is part of our Become a Data Analyst course. Browse the full programme, or get it by email.

Share with

Photo de Romain DE LA SOUCHÈRE

Romain DE LA SOUCHÈRE

Tech Lead, CTO AXI Technologies

Expert Data Engineering et Cloud, Romain affiche plus de 11 ans d'expérience, dont plusieurs années comme Lead Developer sur des solutions Smart Building haute performance. Il y a conçu et mis en production des moteurs de traitement capables d'absorber des centaines de milliers de données de capteurs par minute, ainsi que des bases clusterisées gérant plus de 10 millions de données dynamiques. Certifié Microsoft Azure DevOps Engineer Expert, il maîtrise aussi bien le développement back-end (Python, C#) que le DevOps (Docker, Kubernetes, Terraform) et les agents LLM. Formateur en Python, cloud, DevOps et IA générative appliquée, il forme avec une obsession : Amener chaque apprenant à concevoir et déployer des architectures réellement scalables en production.

» Learn More

Associated trainings

All our trainings
Image de la formation Become a Data Analyst
Become a Data Analyst
6 months
Intermediate
Guarantee

Associated articles

See all our articles