How to use if-elif-else statements in Python?

PythonPythonBeginner
Practice Now

Introduction

Python's if-elif-else statements are fundamental control structures that allow you to make decisions and execute different code blocks based on specific conditions. In this tutorial, we will explore the syntax and structure of these conditional statements, and dive into practical examples to help you master their usage in your Python projects.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") subgraph Lab Skills python/conditional_statements -.-> lab-397699{{"`How to use if-elif-else statements in Python?`"}} end

Understanding If-Elif-Else Statements

In Python, the if-elif-else statements are used to create conditional logic, allowing your program to make decisions based on different conditions. These statements enable you to execute different blocks of code depending on whether a particular condition is true or false.

Basics of Conditional Logic

The basic structure of an if-elif-else statement in Python is as follows:

if condition1:
    ## code to be executed if condition1 is true
elif condition2:
    ## code to be executed if condition1 is false and condition2 is true
else:
    ## code to be executed if both condition1 and condition2 are false

The if statement checks the first condition, and if it is true, the code block under the if statement is executed. If the first condition is false, the program checks the elif condition(s), and if any of them are true, the corresponding code block is executed. If all the if and elif conditions are false, the else block is executed.

Comparison Operators

To create conditions in if-elif-else statements, you can use various comparison operators, such as:

  • == (equal to)
  • != (not equal to)
  • > (greater than)
  • < (less than)
  • >= (greater than or equal to)
  • <= (less than or equal to)

These operators allow you to compare values and create conditions that can be evaluated as either true or false.

Nested Conditional Statements

You can also nest if-elif-else statements within other if-elif-else statements to create more complex conditional logic. This can be useful when you need to make decisions based on multiple conditions.

if condition1:
    if condition2:
        ## code to be executed if both condition1 and condition2 are true
    else:
        ## code to be executed if condition1 is true but condition2 is false
elif condition3:
    ## code to be executed if condition1 is false and condition3 is true
else:
    ## code to be executed if condition1 and condition3 are false

By understanding the basics of if-elif-else statements and conditional logic, you can create powerful and flexible programs in Python that can make decisions and execute different code based on various conditions.

Syntax and Structure of Conditional Logic

Basic If Statement

The basic syntax for an if statement in Python is:

if condition:
    ## code to be executed if the condition is true

The condition can be any expression that evaluates to either True or False.

If-Else Statement

The if-else statement allows you to execute different code blocks based on whether the condition is true or false. The syntax is:

if condition:
    ## code to be executed if the condition is true
else:
    ## code to be executed if the condition is false

If-Elif-Else Statement

The if-elif-else statement allows you to check multiple conditions and execute different code blocks based on which condition is true. The syntax is:

if condition1:
    ## code to be executed if condition1 is true
elif condition2:
    ## code to be executed if condition1 is false and condition2 is true
elif condition3:
    ## code to be executed if condition1 and condition2 are false and condition3 is true
else:
    ## code to be executed if all the conditions are false

The elif and else blocks are optional, and you can have as many elif blocks as needed.

Nested Conditional Statements

You can nest if-elif-else statements within other if-elif-else statements to create more complex conditional logic. The syntax for nested conditional statements is:

if condition1:
    if condition2:
        ## code to be executed if both condition1 and condition2 are true
    else:
        ## code to be executed if condition1 is true but condition2 is false
elif condition3:
    ## code to be executed if condition1 is false and condition3 is true
else:
    ## code to be executed if condition1 and condition3 are false

By understanding the syntax and structure of if-elif-else statements, you can create powerful and flexible conditional logic in your Python programs.

Practical Examples and Use Cases

Grading System

Let's consider a simple grading system example. We can use if-elif-else statements to determine the letter grade based on a student's score:

score = 85

if score >= 90:
    grade = 'A'
elif score >= 80:
    grade = 'B'
elif score >= 70:
    grade = 'C'
elif score >= 60:
    grade = 'D'
else:
    grade = 'F'

print(f"The student's grade is: {grade}")

This code will output: The student's grade is: B

Odd or Even Number

You can use an if-else statement to determine whether a number is odd or even:

num = 17

if num % 2 == 0:
    print(f"{num} is an even number.")
else:
    print(f"{num} is an odd number.")

This code will output: 17 is an odd number.

Nested Conditional Statements

Nested if-elif-else statements can be useful when you need to make decisions based on multiple conditions. For example, let's determine the season based on the month and day:

month = 3
day = 21

if month == 3 and day >= 20 and day <= 31:
    season = 'Spring'
elif month == 6 and day >= 1 and day <= 20:
    season = 'Spring'
elif month == 6 and day >= 21 and day <= 30:
    season = 'Summer'
elif month == 9 and day >= 1 and day <= 20:
    season = 'Summer'
elif month == 9 and day >= 21 and day <= 30:
    season = 'Autumn'
elif month == 12 and day >= 1 and day <= 20:
    season = 'Autumn'
elif month == 12 and day >= 21 and day <= 31:
    season = 'Winter'
elif month == 3 and day >= 1 and day <= 19:
    season = 'Winter'
else:
    season = 'Invalid date'

print(f"The current season is: {season}")

This code will output: The current season is: Spring

By exploring these practical examples, you can see how if-elif-else statements can be used to solve a wide range of problems in your Python programs.

Summary

By the end of this tutorial, you will have a solid understanding of how to leverage if-elif-else statements in Python. You will be able to write more efficient and dynamic code, making informed decisions based on various conditions. This knowledge will be invaluable as you continue to develop your Python programming skills.

Other Python Tutorials you may like