Tutorials  /  Python

Python If/Else Statements Explained: Syntax, Examples, and Best Practices

Ccentron Redaktion · June 2026 ·7 min read ·Python, Tutorial

Conditional logic is one of the core building blocks of programming because it lets your code respond differently depending on whether a specific condition is true or false. In Python, if/else statements are used to direct the flow of execution by running different code blocks according to the result of a condition.

This Python tutorial explains how to work with if/else statements, including the basic syntax, handling several conditions, nested conditions, frequent errors, and recommended best practices.

What Is an If/Else Statement in Python?

In Python, an if/else statement is a control structure that runs one block of code when a condition evaluates to True, and runs a different block when that condition evaluates to False.

VM

Matching infrastructure at centron

Scripts and services eventually need an environment that keeps running: ccloud³ VMs from €3.12 per month, billed by the hour. Rent a cloud server →

Basic Syntax

YAML
if condition:
    # Code to execute if condition is True
else:
    # Code to execute if condition is False

Example:

Python
age = int(input("Enter your age: "))
if age >= 18:
    print("You are eligible to vote.")
else:
    print("You are not eligible to vote.")

Using if-elif-else for Multiple Conditions

When you need to evaluate more than one possible condition, Python’s if-elif-else structure is very useful. The elif keyword, which means “else if,” makes it possible to test extra conditions when the first if condition is not satisfied. This creates a cleaner and more organized way to manage more advanced decision-making in your programs.

Example:

Python
marks = int(input("Enter your marks: "))
if marks >= 90:
    print("Grade: A")
elif marks >= 75:
    print("Grade: B")
elif marks >= 60:
    print("Grade: C")
else:
    print("Grade: F")

One-Line If/Else Statements (Ternary Operator)

Python also supports a shorter format for simple conditional expressions. This is commonly referred to as the ternary operator. It allows you to write a one-line condition that returns one value when the condition is true and another when it is false.

Example:

Python
num = int(input("Enter a number: "))
result = "Even" if num % 2 == 0 else "Odd"
print(result)

Nested If Statements

Nested if statements let you test additional conditions inside another if block. This is especially helpful when several related checks must happen before a certain piece of code should run. By nesting conditions, you can organize more detailed decision-making in a structured way.

Example:

Python
num = int(input("Enter a number: "))
if num > 0:
    if num % 2 == 0:
        print("Positive Even Number")
    else:
        print("Positive Odd Number")
else:
    print("Negative Number or Zero")

Handling Multiple Conditions with and, or, not

Python includes logical operators that allow you to combine several conditions into a single expression. This makes it possible to build more advanced logic in your code. The available logical operators are and, or, and not.

Example:

Python
temp = int(input("Enter the temperature: "))

if temp > 30 and temp < 40:
    print("It's a hot day!")
else:
    print("It's not a hot day.")

# Example using 'or' operator
if temp > 30 or temp < 10:
    print("Temperature is extreme!")

# Example using 'not' operator
if not (temp > 30 and temp < 40):
    print("It's not a hot day.")

When to Use if/else vs. match-case (Python 3.10+)

Starting with Python 3.10, the match-case statement offers another way to perform certain kinds of conditional checks. This feature is particularly helpful when you want to compare one variable against multiple possible values without relying on long or deeply nested if/else blocks. In many situations, match-case can make code shorter, clearer, and easier to maintain.

Example of match-case:

Python
def get_day_name(day):
    match day:
        case 1:
            return "Monday"
        case 2:
            return "Tuesday"
        case _:
            return "Invalid day"

Comparison of if/else and match-case Statements

Feature if/else Statements match-case Statement
Syntax More detailed More compact
Readability May become harder to follow with many conditions Usually easier to read when checking many values
Use Cases Good for straightforward conditional checks Best for evaluating multiple values of one variable
Performance No major difference No major difference
Python Version Available in all Python versions Introduced in Python 3.10

When to Use Each

Use if/else statements when you need simple condition checks or when your code must run on Python versions earlier than 3.10.

Use match-case when you are comparing one variable against several possible values, especially when working with Python 3.10 or newer.

Common Mistakes and Debugging Tips

1. Indentation Errors

Python relies on indentation to define code blocks. If indentation is missing or inconsistent, the program will raise an error.

Example:

Python
if True:
    print("This will cause an error!")  # IndentationError

Fixed Example:

Python
if True:
    print("This will not cause an error!")

2. Misuse of Boolean Operators

Using logical operators incorrectly can produce results you did not expect.

Example:

Code
if age >= 18 and age <= 60:  # Correct
if age >= 18 or <= 60:  # Incorrect

3. Handling Unexpected Input

When accepting user input, it is a good idea to use exception handling to catch invalid values.

Python
try:
    num = int(input("Enter a number: "))
except ValueError:
    print("Invalid input! Please enter a number.")

4. Error Handling with If Else Statements

You can combine error handling with if/else-related logic in Python. Here is an example showing how this works:

Python
try:
    # Code that may raise an exception
    num = int(input("Enter a number: "))
except ValueError:
    # Code to handle the exception
    print("Invalid input! Please enter a number.")
else:
    # Code to execute if no exception is raised
    print("You entered a valid number.")
finally:
    # Code to execute regardless of whether an exception was raised
    print("Thank you for using this program.")

FAQs

1. Can I use multiple elif conditions in Python?

Yes, you can include as many elif conditions as necessary when you need to test multiple possibilities.

YAML
if condition1:
    # code to execute if condition1 is True
elif condition2:
    # code to execute if condition2 is True
elif condition3:
    # code to execute if condition3 is True
else:
    # code to execute if all conditions are False

2. What is the difference between if and elif in Python?

An if statement is evaluated first. Only when the if condition is false will Python move on to evaluate the elif conditions in sequence.

Here is a table that shows the differences:

if Statement elif Statement
Checked first every time Checked only when the if condition is false
Can appear in multiple separate if statements Can also appear multiple times in the same chain
Can be followed by an else block Can also be followed by an else block

Keep in mind that only one code block is executed. If the if condition is true, Python skips the elif and else blocks. If the if condition is false, Python checks the elif block. If the elif condition is also false, the else block is executed.

Here is an example showing how if, elif, and else work together in Python:

Python
num = int(input("Enter a number: "))

if num > 0:
    print("The number is positive.")
elif num == 0:
    print("The number is zero.")
else:
    print("The number is negative.")

3. How do I avoid indentation errors in Python if statements?

Ensure that every code block is indented correctly by using four spaces or one tab consistently.

4. What is the best way to handle complex if/else conditions?

To improve readability, split complicated conditions into smaller helper functions or combine expressions carefully with logical operators.

Here is an example of using logical operators in Python:

Python
num = int(input("Enter a number: "))

if num > 0 and num % 2 == 0:
    print("The number is positive and even.")
elif num > 0 and num % 2 != 0:
    print("The number is positive and odd.")
elif num == 0:
    print("The number is zero.")
else:
    print("The number is negative.")

5. Is there a switch-case alternative in Python?

Yes, Python 3.10 introduced match-case, which works in a similar way to a switch statement.

Here is an example of using match-case in Python:

Python
def match_case_example(argument):
    match argument:
        case 1:
            print("You chose 1.")
        case 2:
            print("You chose 2.")
        case 3:
            print("You chose 3.")
        case _:
            print("Invalid choice.")

Conclusion

A solid understanding of if/else statements is essential for making decisions in Python programming. Once you become confident with conditional logic, you can create code that is cleaner, more effective, and less prone to errors.

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie Python
Teilen
Noch offene Fragen?

Unser Team hilft Ihnen bei Ihrem konkreten Setup weiter – von Menschen, die die Plattform selbst betreiben.

War dieses Tutorial hilfreich?

Ihre Antwort wird anonym gespeichert und hilft uns, die Tutorials zu verbessern.

Kommentare

Noch keine Kommentare – stellen Sie die erste Frage zu diesem Tutorial.

Zum Kommentieren anmelden

Kommentare stehen centron-Kunden offen. Melden Sie sich in Ihrem Konto an, um eine Frage zu diesem Tutorial zu stellen.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren