Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • šŸ“ Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • šŸ“ Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • šŸ“ Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • šŸ“ Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • šŸ“ While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • šŸ“ For Each Assignments
    • šŸ“ All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • šŸ“ Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • šŸ“ Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • šŸ“ Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • šŸ“ Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • šŸ“ Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • šŸ“ Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • šŸ“ Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • šŸ“ Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • šŸ“ Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • šŸ“ Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • šŸ“ Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • šŸ“ Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • šŸ“ Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • šŸ“ Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • šŸ“ Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • šŸ“ Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • šŸ“ Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • šŸ“ Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • šŸ“ Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

šŸ“Š Python if-elif-else Ladder: Complete Guide

Python if-elif-else Ladder - Complete Guide

The if-elif-else ladder lets you choose between multiple paths — like a menu of options.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
šŸ“‘ On this page:
  • What is the if-elif-else Ladder?
  • Syntax of if-elif-else Ladder
  • Flowchart of if-elif-else Ladder
  • Positive, Negative, or Zero
  • Checking Data Type
  • Grade Calculator
  • Common Mistakes
  • Try It Yourself
  • Quick Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
šŸ“š What You'll Learn Here
  • What the if-elif-else ladder is — multi-way decision making
  • Syntax of if-elif-else — checking multiple conditions in order
  • Flowchart of if-elif-else — visualizing the flow
  • Positive, Negative, or Zero — classic example
  • Checking Data Type — using type() with elif
  • Grade Calculator — real-world application
  • Common mistakes — and how to avoid them

What is the if-elif-else Ladder?

The if-elif-else ladder is a powerful decision-making structure that allows you to check multiple conditions in sequence. When you need to choose between more than two options, the if-elif-else ladder is your go-to tool.

šŸ’” Key insight: Think of the if-elif-else ladder like a multiple-choice question. Each elif is like an option — as soon as one option is correct, the rest are skipped. The else is like "none of the above."

The elif statement is optional and there can be an arbitrary number of elif statements following an if. The "elif" statement is a combination of else and if. It must come after an if statement and before an else.

Syntax of if-elif-else Ladder

# Syntax of if-elif-else Ladder
if condition1:
    # Execute this block if condition1 is true
elif condition2:
    # Execute this block if condition1 is false and condition2 is true
elif condition3:
    # Execute this block if condition1 and condition2 are false and condition3 is true
else:
    # Execute this block if all conditions are false

# Example
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"Your grade is {grade}")

šŸ“– Breaking it down: Python checks conditions from top to bottom. The first condition that evaluates to True executes its block, and the rest are skipped. If none are true, the else block executes (if present).

āš ļø Important: The else block is optional but recommended. It ensures that every possible condition has a response, making your program more robust.

Flowchart of if-elif-else Ladder

Let's visualize how the if-elif-else ladder works:

Flowchart:

    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
    │    START    │
    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
           ā–¼
    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
    │  Condition1 │
    │   (True?)   │─── Yes ──► ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”˜            │ Execute if   │
           │                   │   block      │
           No                  ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
           ā–¼                          │
    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”                  │
    │  Condition2 │─── Yes ──► ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
    │   (True?)   │            │ Execute elif │
    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”˜            │   block 1    │
           │                   ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
           No                          │
           ā–¼                          │
    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”                  │
    │  Condition3 │─── Yes ──► ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
    │   (True?)   │            │ Execute elif │
    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”˜            │   block 2    │
           │                   ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
           No                          │
           ā–¼                          │
    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”                  │
    │   else      │                  │
    │   block     │                  │
    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”˜                  │
           │                          │
           ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
                      ā–¼
             ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
             │    END      │
             ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜

Example 1: Positive, Negative, or Zero

Let's check if a number is positive, negative, or zero:

# Check if number is positive, negative, or zero
p = 8

if p < 0:
    print(p, "is a Negative Number")
elif p > 0:
    print(p, "is a Positive Number")
else:
    print("The given number is Zero")

# Output:
# 8 is a Positive Number

šŸ“– Explanation:
1. We initialize variable p with value 8.
2. if p < 0: checks if the number is negative — False.
3. elif p > 0: checks if the number is positive — True.
4. The elif block executes and prints 8 is a Positive Number.
5. The else block is skipped because a condition was already true.

Example 2: Checking Data Type

This example uses if-elif-else to determine the data type of a variable:

# Check data type of a variable
x = 3 + 6j

if type(x) == int:
    print("Data Type of x is Integer")
elif type(x) == float:
    print("Data Type of x is Float")
elif type(x) == complex:
    print("Data Type of x is Complex")
elif type(x) == bool:
    print("Data Type of x is Bool")
elif type(x) == str:
    print("Data Type of x is String")
elif type(x) == tuple:
    print("Data Type of x is Tuple")
elif type(x) == dict:
    print("Data Type of x is Dictionary")
elif type(x) == list:
    print("Data Type of x is List")
else:
    print("Unknown Data Type")

# Output:
# Data Type of x is Complex

šŸ“– Explanation: The type() function returns the data type of a variable. This example uses multiple elif conditions to check against different data types. Since x is a complex number, the third condition matches and prints the result.

Example 3: Grade Calculator

This is a practical example that calculates a student's grade based on their score:

# Grade Calculator using if-elif-else
score = int(input("Enter your score: "))

if score >= 90:
    grade = "A"
    message = "Excellent work!"
elif score >= 80:
    grade = "B"
    message = "Good job!"
elif score >= 70:
    grade = "C"
    message = "Keep improving!"
elif score >= 60:
    grade = "D"
    message = "Needs attention!"
else:
    grade = "F"
    message = "Please seek help!"

print(f"Your grade is {grade}. {message}")

# Output:
# Enter your score: 85
# Your grade is B. Good job!

Common Mistakes to Avoid

āŒ Mistake 1: Wrong Order of Conditions

The order of elif conditions matters. Put the most specific conditions first.

# WRONG (broad condition first)
score = 95
if score >= 60:
    grade = "D"  # This will run!
elif score >= 90:
    grade = "A"  # Never reached

# CORRECT (specific condition first)
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

āŒ Mistake 2: Using Multiple If Instead of elif

Using multiple if statements checks all conditions, which can cause unintended multiple executions.

# WRONG (multiple ifs)
x = 85
if x >= 80:
    print("Grade B")
if x >= 90:
    print("Grade A")  # This won't run, but all ifs are checked

# CORRECT (if-elif-else)
if x >= 90:
    print("Grade A")
elif x >= 80:
    print("Grade B")
else:
    print("Other grade")

Try It Yourself!

Experiment with the if-elif-else ladder directly in your browser:

Loading Pyodide... 0%
Python Code Editor
========================================
IF-ELIF-ELSE LADDER
========================================

1. CHECK NUMBER TYPE
8 is Positive

2. GRADE CALCULATOR
Score: 85, Grade: B

3. DATA TYPE CHECK
x is Complex

āœ… Explore different if-elif-else conditions!
šŸ†

šŸŽ‰ You've Mastered Python if-elif-else Ladder!

You understand multi-way decision making with if-elif-else. This is essential for handling multiple conditions in Python!

Quick Quiz – Test Your Knowledge

1. What does the elif keyword stand for?
2. How many elif statements can you have in a ladder?
3. What happens when a condition in elif is true?
4. What is the correct syntax for an elif statement?
5. Is the else block required in an if-elif-else ladder?

Frequently Asked Questions

šŸ¤” What is the difference between if-elif-else and multiple if statements? ā–¼

if-elif-else runs only the first true condition and skips the rest. Multiple if statements check every condition independently, which can cause unintended multiple executions.

šŸ”§ Can I have multiple elif statements? ā–¼

Yes! You can have as many elif statements as you need. Just make sure the order is logical — put the most specific conditions first.

šŸ“ What happens if no elif conditions are true and there is no else? ā–¼

If no conditions are true and there's no else, nothing executes. The program continues with the next statement after the if-elif block. This is valid syntax but sometimes unexpected.

šŸ“Š Can I use logical operators in elif conditions? ā–¼

Yes! You can combine conditions using and, or, and not in any elif condition. For example: elif age >= 18 and has_license:.

⚔ What is the maximum number of elif statements allowed? ā–¼

There is no maximum limit. You can have as many elif statements as needed. However, for readability, consider using other structures (like dictionaries or switch-case in Python 3.10+) if you have many conditions.

šŸŽÆ When should I use if-elif-else instead of if-else? ā–¼

Use if-elif-else when you have more than two mutually exclusive conditions. Use if-else for simple two-way decisions. The ladder is perfect for grading systems, menu selection, and classification problems.

šŸ“š Where to Go From Here

Now that you've mastered the if-elif-else ladder, here are the next topics to explore:

šŸ“ Nested if Statements

Master complex decision making with nested if statements.

Learn More →

šŸ“ Shorthand if-else

Learn the ternary operator for concise conditional expressions.

Learn More →

šŸ“ Conditional Assignments

Practice what you've learned with real coding challenges.

Practice →
šŸ“– Interview & FAQ Resources
  • Python Syntax & Variables Interview Questions
  • SQL - Displaying Data from Multiple Tables FAQ
  • SQL Window Functions & Analytic Functions FAQ
  • Python Data Types Interview Questions
  • Python Tuples and Sets Interview Questions
  • Java Basic Input/Output Interview Questions
  • Java Advanced Threads and Concurrency Interview Questions
Previous: if-else Statement Next: Nested if →