Python if, elif and else operators: a complete guide

онлайн тренажер по питону
Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Conditional statements in Python

if, elif and else branching statements in Python

The if, elif and else branching statements in Python form the foundation of any program flow-control logic. They allow different blocks of code to be executed depending on conditions.

In this article you will learn how the if-elif-else construct works. We will cover when to use each part. You will also learn how to avoid mistakes and write readable, efficient code.

What conditional statements are in Python

Conditional statements allow code to run only when a specific condition is met. These statements form the basis of program logic and enable interactive programs.

if condition:
    # code runs if condition is true
elif another_condition:
    # code runs if the first one didn't hold, but this one does
else:
    # runs if none of the conditions were met

Conditional statements work with boolean expressions. These expressions return True or False. Depending on the result, the corresponding block of code is executed.

Basic syntax of the if statement

The simplest if conditional executes a block of code only when the condition is true:

x = 10
if x > 5:
    print("x is greater than 5")

In this example x > 5 is a boolean expression. When it returns True, the body of the if block runs. Note the colon after the condition and the indentation on the following line.

Using else

The else clause provides an alternative execution path:

x = 2
if x > 5:
    print("x is greater than 5")
else:
    print("x is less than or equal to 5")

The else block is optional. It runs only when the if condition is False. This allows handling all remaining cases.

Multiple conditions with elif

The elif clause allows checking additional conditions:

x = 0
if x > 0:
    print("Positive number")
elif x == 0:
    print("Zero")
else:
    print("Negative number")

elif is short for else if. In Python it is the official syntax for multiple-condition checks. Any number of elif blocks can be used.

How if, elif, else work

Python evaluates conditions sequentially from top to bottom. This process follows a clear execution logic.

First the condition in the if block is checked. If it is true, the corresponding code runs and the remaining blocks are skipped.

If the if condition is false, Python proceeds to check the elif conditions in order. As soon as a true condition is found, its block runs.

If none of the if and elif conditions are met, the else block runs. The else block is optional and may be omitted.

Important to remember: only one block of code will execute, even if multiple conditions could be true simultaneously.

Practical usage examples

Knowledge grading system

score = 85
if score >= 90:
    print("Excellent")
elif score >= 75:
    print("Good")
elif score >= 60:
    print("Satisfactory")
else:
    print("Unsatisfactory")

In this example conditions are checked in descending order. This ensures correct category assignment.

Checking if a number is even

n = 7
if n % 2 == 0:
    print("Even")
else:
    print("Odd")

The % operator returns the remainder of division. If the remainder is zero, the number is even.

Determining age category

age = 25
if age < 18:
    print("Minor")
elif age < 65:
    print("Working age")
else:
    print("Retirement age")

Complex conditions and logical operators

Python allows combining conditions using logical operators:

and - logical AND (all conditions must be true)

or - logical OR (at least one condition must be true)

not - logical NOT (inverts the condition)

x = 10
y = 20
if x > 5 and y > 15:
    print("Both conditions are met")

Precedence of logical operators

When using multiple logical operators, understanding precedence is important:

age = 25
has_license = True
has_car = False

if age >= 18 and has_license or has_car:
    print("Can drive")

For clarity it is recommended to use parentheses:

if (age >= 18 and has_license) or has_car:
    print("Can drive")

Nested conditions

You can nest one conditional inside another:

x = 10
if x > 0:
    if x < 100:
        print("x is between 0 and 100")
    else:
        print("x is greater than or equal to 100")
else:
    print("x is less than or equal to 0")

However, overusing nesting can make code hard to read. It's better to use logical operators:

x = 10
if 0 < x < 100:
    print("x is between 0 and 100")

Comparison operators

Python supports various comparison operators in conditions:

== - equal

!= - not equal

> - greater than

< - less than

>= - greater than or equal to

<= - less than or equal to

in - membership (for sequences)

is - object identity

name = "Python"
if name == "Python":
    print("This is Python!")

numbers = [1, 2, 3, 4, 5]
if 3 in numbers:
    print("Number 3 is in the list")

Comparison specifics in Python

Python allows chaining comparisons:

x = 15
if 10 < x < 20:
    print("x is between 10 and 20")

This is equivalent to:

if x > 10 and x < 20:
    print("x is between 10 and 20")

Ternary operator in Python

Pythonic style offers a compact if-else form for simple cases:

x = 5
result = "even" if x % 2 == 0 else "odd"

This is a more concise alternative to the full conditional:

if x % 2 == 0:
    result = "even"
else:
    result = "odd"

The ternary operator should be used only for simple conditions. Complex logic is better expressed in full form for readability.

Common mistakes and solutions

Indentation problems

Python uses indentation to define code blocks. Incorrect indentation raises IndentationError:

# Incorrect
x = 5
if x > 0:
print("Positive")  # Indentation error

# Correct
x = 5
if x > 0:
    print("Positive")  # 4 spaces or 1 tab

Confusing assignment with comparison

A common error is using = instead of == in conditions:

# Incorrect
x = 5
if x = 5:  # Syntax error
    print("x equals 5")

# Correct
x = 5
if x == 5:  # Comparison
    print("x equals 5")

Wrong type comparisons

Comparing different data types can lead to bugs:

# Potential issue
user_input = "5"  # String
number = 5        # Integer

if user_input == number:  # False, types differ
    print("Equal")

# Correct approach
if int(user_input) == number:
    print("Equal")

Inefficient use of multiple ifs

When conditions are mutually exclusive, use elif instead of multiple ifs:

# Inefficient
score = 85
if score >= 90:
    grade = "A"
if score >= 80 and score < 90:  # Redundant check
    grade = "B"
if score >= 70 and score < 80:  # Redundant check
    grade = "C"

# Efficient
score = 85
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"

Best programming practices

Principles for writing readable code

Use elif instead of multiple ifs when conditions exclude each other. This improves performance and readability.

Break complex conditions into simpler parts. Long conditions with multiple logical operators are better split across several lines or variables.

# Hard to read
if user.age >= 18 and user.has_license and user.insurance_valid and not user.has_violations:
    allow_driving = True

# More readable
is_adult = user.age >= 18
has_valid_documents = user.has_license and user.insurance_valid
has_clean_record = not user.has_violations

if is_adult and has_valid_documents and has_clean_record:
    allow_driving = True

Reducing nesting

Avoid deep nesting of conditions. Use logical operators and early returns:

# Deep nesting
def process_user(user):
    if user is not None:
        if user.is_active:
            if user.has_permission:
                return "Access granted"
            else:
                return "No permission"
        else:
            return "User inactive"
    else:
        return "User not found"

# Simplified version
def process_user(user):
    if user is None:
        return "User not found"
    if not user.is_active:
        return "User inactive"
    if not user.has_permission:
        return "No permission"
    return "Access granted"

Explicitly handle all cases

Always consider whether else is needed. Sometimes it is better to handle all possible cases explicitly with elif:

# Using else
day = "Monday"
if day in ["Saturday", "Sunday"]:
    print("Weekend")
else:
    print("Weekday")

# Explicit handling of all cases
weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
weekend = ["Saturday", "Sunday"]

if day in weekend:
    print("Weekend")
elif day in weekdays:
    print("Weekday")
else:
    print("Invalid day")

Application in real projects

Data validation

def validate_email(email):
    if not isinstance(email, str):
        return False, "Email must be a string"
    elif "@" not in email:
        return False, "Email must contain @"
    elif len(email) < 5:
        return False, "Email is too short"
    elif email.count("@") != 1:
        return False, "Email must contain only one @"
    else:
        return True, "Email is valid"

Handling user input

def process_command(command):
    command = command.lower().strip()
    
    if command in ["quit", "exit", "q"]:
        return "Exiting program"
    elif command in ["help", "h"]:
        return "Available commands: help, quit, status"
    elif command == "status":
        return "Program is running normally"
    else:
        return f"Unknown command: {command}"

Application configuration

def setup_logging(environment):
    if environment == "production":
        log_level = "ERROR"
        log_file = "/var/log/app.log"
    elif environment == "staging":
        log_level = "WARNING"
        log_file = "/tmp/app_staging.log"
    elif environment == "development":
        log_level = "DEBUG"
        log_file = "app_dev.log"
    else:
        log_level = "INFO"
        log_file = "app.log"
    
    return log_level, log_file

Alternatives to conditional statements

Using dictionaries

In some cases dictionaries can replace long elif chains:

# Instead of many elifs
def get_day_name(day_number):
    if day_number == 1:
        return "Monday"
    elif day_number == 2:
        return "Tuesday"
    elif day_number == 3:
        return "Wednesday"
    # ... and so on

# Using a dictionary
def get_day_name(day_number):
    days = {
        1: "Monday",
        2: "Tuesday",
        3: "Wednesday",
        4: "Thursday",
        5: "Friday",
        6: "Saturday",
        7: "Sunday"
    }
    return days.get(day_number, "Invalid day number")

Match-case pattern (Python 3.10+)

In modern Python versions the match-case statement is available:

def process_status_code(code):
    match code:
        case 200:
            return "OK"
        case 404:
            return "Not Found"
        case 500:
            return "Internal Server Error"
        case _:
            return "Unknown status"

Frequently Asked Questions

What does elif mean in Python?

elif is short for else if. It is used to add additional conditions to an if-else construct. Unlike some other languages, Python uses elif instead of else if.

Can you use multiple elif blocks?

Yes, Python allows any number of elif blocks. They are checked sequentially from top to bottom until a true condition is found.

Is there a switch statement in Python?

Classic Python does not have a switch statement, but similar functionality can be implemented with if-elif-else or dictionaries. Since Python 3.10, the match-case statement is available and provides switch-like behavior.

How is elif different from several ifs in a row?

An elif condition is evaluated only if previous conditions were false, whereas separate if statements are evaluated independently. Using elif improves performance and logical correctness.

How to compare strings in conditions?

Strings are compared the same way as numbers using ==, !=, <, >. Python compares strings lexicographically (alphabetical order):

if name == "Python":
    print("This is Python!")

if "apple" < "banana":
    print("apple comes before banana alphabetically")

Conclusion

The if-elif-else construct is a cornerstone of logic in Python. It provides simplicity, readability and power to program code. Understanding its structure and style helps create reliable and predictable programs.

Key principles for working with conditional statements include correct use of indentation, logical composition of conditions and choosing an appropriate style for the task. The ternary operator fits simple cases, while combining conditions with logical operators enables complex logic without sacrificing readability.

News