How to Use If, Elif, and Else in Python: Master Conditional Logic

Published on: May 8, 2026
Reading time: 6 minutes
Imagem de um quadro negro com várias interrogações no lugar de lâmpadas, e uma lâmpada conectada no meio

Conditional statements are one of the most important parts of programming. They allow your code to make decisions based on specific conditions.

In Python, you use if, elif, and else to control the flow of your programs. These statements help your applications react to user input, compare values, validate data, and much more.

If you are learning Python, mastering conditional logic is essential. Almost every real-world project uses conditions in some way.

Before diving deeper into conditional statements, it helps to understand programming logic with Python and how Boolean values work in Python.

What Is Conditional Logic in Python?

Conditional logic allows a program to execute different actions depending on whether a condition is true or false.

For example, imagine a login system:

  • If the password is correct, the user logs in.
  • Else, the system displays an error message.

Python evaluates conditions using Boolean values:

  • True
  • False

Here is a simple example:

Python
age = 18

if age >= 18:
    print("You are an adult")

The program checks if age is greater than or equal to 18. If the condition is true, Python executes the code inside the block.

Understanding the if Statement

The if statement is the foundation of conditional logic in Python.

It checks whether a condition is true.

Basic syntax:

Python
if condition:
    # code to execute

Example:

Python
temperature = 30

if temperature > 25:
    print("It is a hot day")

In this case, Python evaluates the condition:

Is temperature greater than 25?

Since the answer is true, the message appears.

Indentation is extremely important in Python. The indented code belongs to the conditional block.

If you still struggle with spacing, read this guide about Python indentation.

How the else Statement Works

The else statement runs when the if condition is false.

Example:

Python
age = 15

if age >= 18:
    print("Access granted")
else:
    print("Access denied")

The output will be:

Access denied

This happens because the condition is false.

The else block acts as a fallback option.

You can think of it like this:

  • If something is true, do this.
  • Else, do something different.

Using Elif for Multiple Conditions

The elif statement means “else if”.

It allows you to check multiple conditions in sequence.

Example:

Python
score = 85

if score >= 90:
    print("Excellent")
elif score >= 70:
    print("Good")
else:
    print("Needs improvement")

The result will be:

Good

Python checks each condition from top to bottom.

  1. Is score greater than or equal to 90?
  2. No.
  3. Is score greater than or equal to 70?
  4. Yes.
  5. Execute that block.

Once Python finds a true condition, it stops checking the remaining conditions.

Comparison Operators Used with If Statements

Conditional statements often use comparison operators.

OperatorMeaningExample
==Equal tox == 5
!=Not equal tox != 5
>Greater thanx > 5
<Less thanx < 5
>=Greater or equalx >= 5
<=Less or equalx <= 5

Example:

Python
number = 10

if number != 5:
    print("The number is not 5")

If you want a deeper understanding of Python operators, check this article about operators in Python.

Combining Conditions with and, or, and not

You can combine multiple conditions using logical operators.

Using and

The condition becomes true only if all expressions are true.

Python
age = 20
has_ticket = True

if age >= 18 and has_ticket:
    print("Entry allowed")

Using or

The condition becomes true if at least one expression is true.

Python
day = "Saturday"

if day == "Saturday" or day == "Sunday":
    print("Weekend")

Using not

The not operator reverses the Boolean value.

Python
logged_in = False

if not logged_in:
    print("Please log in")

These operators help you create smarter and more flexible programs.

Nested If Statements in Python

You can place one if statement inside another.

This is called a nested conditional.

Python
age = 22
has_id = True

if age >= 18:
    if has_id:
        print("Access approved")

Python first checks the outer condition.

If it is true, Python checks the inner condition.

Nested conditions are useful for:

  • User authentication
  • Game logic
  • Menu systems
  • Data validation

However, avoid excessive nesting because it can make your code difficult to read.

Tip: If your conditional logic becomes too complex, consider splitting code into functions.

You can learn more about organizing code in this guide about functions in Python.

Common Mistakes Beginners Make

Many beginners make small mistakes when working with conditional logic.

1. Forgetting the Colon

Wrong:

Python
if age > 18
    print("Adult")

Correct:

Python
if age > 18:
    print("Adult")

2. Incorrect Indentation

Wrong indentation causes errors.

Python
if True:
print("Hello")

Correct:

Python
if True:
  print("Hello")

3. Using = Instead of ==

Wrong:

Python
if age = 18:

Correct:

Python
if age == 18:

The = operator assigns values.

The == operator compares values.

Many syntax problems come from simple mistakes like these. This article about Python syntax errors can help you troubleshoot them.

Real-World Examples of Conditional Logic

Conditional statements appear in almost every application.

Password Validation

Python
password = input("Enter password: ")

if password == "python123":
    print("Access granted")
else:
    print("Incorrect password")

Checking Even or Odd Numbers

Python
number = 7

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

Simple Grade System

Python
grade = 92

if grade >= 90:
    print("A")
elif grade >= 80:
    print("B")
elif grade >= 70:
    print("C")
else:
    print("F")

These examples show how conditional logic solves practical problems.

Best Practices for Writing Clean Conditional Logic

Good code should be easy to read and maintain.

Here are some useful tips:

  • Keep conditions simple
  • Use meaningful variable names
  • Avoid deeply nested conditions
  • Write clear comparison expressions
  • Test different inputs

Example of readable code:

Python
user_age = 25

if user_age >= 18:
    print("Adult user")

Bad example:

Python
x = 25

if x >= 18:
    print("Adult user")

Descriptive names improve readability.

The official Python documentation about control flow also provides excellent examples and best practices.

When to Use Match Case Instead of If Elif Else

Python introduced match-case in Python 3.10.

It can replace long chains of if-elif-else statements in some situations.

Example:

Python
status = 404

match status:
    case 200:
        print("Success")
    case 404:
        print("Page not found")
    case 500:
        print("Server error")

This syntax can make some programs cleaner and easier to understand.

You can explore this feature further in this guide about match-case in Python.

Conclusion

Learning how to use if, elif, and else in Python is a major step for every beginner.

Conditional logic gives your programs the ability to make decisions. Without it, your applications would only execute code in a fixed order.

With conditional statements, you can:

  • Validate user input
  • Create interactive programs
  • Build login systems
  • Control game behavior
  • Handle real-world situations

Practice writing small programs using different conditions. The more you experiment, the more natural conditional logic will become.

You can also explore the official Python website for tutorials, guides, and beginner resources.

Frequently Asked Questions (FAQ)

1. What does if mean in Python?

It checks if a condition is true and runs specific code.

2. What is the difference between if and elif?

If starts the condition. Elif checks additional conditions.

3. Is else required in Python?

No. You can use if without else.

4. Can I use multiple elif statements?

Yes. Python allows many elif blocks in one structure.

5. What type of value does if check?

It checks Boolean values like True or False.

6. Why is indentation important in Python?

Indentation defines which code belongs to each block.

7. Can conditions use strings?

Yes. Python can compare text values easily.

8. What happens if all conditions are false?

The else block runs if it exists.

9. Can I combine conditions in Python?

Yes. Use and, or, and not operators.

10. Is match-case better than if-elif-else?

Sometimes. It works well for many fixed value comparisons.

Share:

Facebook
WhatsApp
Twitter
LinkedIn

Article content

    Related articles

    ícone de loop com o texto 'While' abaixo
    Fundamentals
    Foto do Leandro Hirt

    How to Use While Loops in Python with Practical Examples

    Learning how to use a while loop in Python is one of the biggest steps for beginners. While loops help

    Ler mais

    Tempo de leitura: 6 minutos
    08/05/2026
    notebook com código saindo da tela
    Fundamentals
    Foto do Leandro Hirt

    How to Use Variables in Python: A Complete Beginner’s Guide

    Variables are one of the first things every programmer learns in Python. They help you store information, reuse data, and

    Ler mais

    Tempo de leitura: 6 minutos
    08/05/2026
    Imagem do Logo do Python dentro de um celular
    Fundamentals
    Foto do Leandro Hirt

    How to Run Python on Your Phone: A Step-by-Step Guide

    Learning Python no longer requires a powerful desktop computer. Today, you can write, test, and run Python code directly from

    Ler mais

    Tempo de leitura: 7 minutos
    08/05/2026
    Homem pensando olhando para o logo do Python
    Fundamentals
    Foto do Leandro Hirt

    Python for Beginners: Learn to Code from Scratch

    Python is one of the best programming languages for beginners. It has a simple syntax, a huge community, and many

    Ler mais

    Tempo de leitura: 7 minutos
    08/05/2026
    Homem pensando à frente de um notebook com código de programação
    Fundamentals
    Foto do Leandro Hirt

    Python Indentation Made Simple: A Beginner’s Guide

    When you start learning Python, one concept appears almost immediately: indentation. Many beginners feel confused when they see spaces changing

    Ler mais

    Tempo de leitura: 6 minutos
    08/05/2026
    texto 'Roadmap' com o logo do Python à direita
    Fundamentals
    Foto do Leandro Hirt

    Master Python in 2026: The Ultimate Step-by-Step Roadmap

    If you want to learn Python in 2026, you are making a great choice. Python is the most popular programming

    Ler mais

    Tempo de leitura: 11 minutos
    08/05/2026