How To Write If Else In Python

8 min read

Learning how to write if else in Python is one of the most important skills for anyone starting with programming. Also, conditional statements allow your code to make decisions, respond to user input, validate data, and control the flow of a program. Without if, else, and related structures such as elif, your Python scripts would always run in the same order, no matter what values they receive.

In Python, an if else statement is used to execute one block of code when a condition is true and another block when the condition is false. This simple idea becomes incredibly powerful when combined with variables, functions, loops, and user input. Whether you are building a calculator, a game, a web application, or an automation script, understanding conditional logic is essential.

This changes depending on context. Keep that in mind Small thing, real impact..

This guide explains how to write if else in Python step by step, with clear examples, common mistakes, and practical tips.

What Is an If Else Statement in Python?

An if else statement is a control structure that lets Python choose between two paths. If that condition evaluates to True, Python runs the indented block under if. The if part checks a condition. If the condition is False, Python runs the block under else That's the part that actually makes a difference..

In simple terms:

  • if means “do this when something is true.”
  • else means “do this when the condition is not true.”

As an example, imagine a program that checks whether a user is old enough to vote. In real terms, if the user is 18 or older, the program says they can vote. Otherwise, it says they cannot.

This decision-making ability is what makes Python useful for real-world tasks Not complicated — just consistent..

Basic Syntax of If Else in Python

The basic syntax for an if else statement in Python looks like this:

if condition:
    # code runs if condition is True
else:
    # code runs if condition is False

A few important details:

  1. The keyword if starts the condition.
  2. The condition is followed by a colon :
  3. The code inside each block must be indented.
  4. Python uses indentation to define blocks of code.

Indentation is not just a style preference in Python. It is part of the language syntax. If your indentation is wrong, Python will raise an error Most people skip this — try not to..

How to Write a Simple If Else in Python

Let’s start with a very simple example.

age = 20

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

In this example:

  • The variable age is set to 20.
  • The condition age >= 18 checks whether the age is greater than or equal to 18.
  • Since 20 >= 18 is True, Python prints You are an adult.

If we change the value of age to 15, the output becomes:

age = 15

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

Output:

You are not an adult.

This is the foundation of how to write if else in Python. You create a condition, then define what should happen when the condition is true or false.

Understanding Conditions in Python

A condition in an if else statement is usually a Boolean expression. A Boolean expression evaluates to either True or False.

Common comparison operators include:

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

Example:

score = 85

if score >= 60:
    print("Pass")
else:
    print("Fail")

Here, score >= 60 is the condition. Since 85 >= 60 is true, the program prints Pass.

You can also combine conditions using logical operators:

  • and means both conditions must be true.
  • or means at least one condition must be true.
  • not reverses the truth value.

Example:

age = 22
has_ticket = True

if age >= 18 and has_ticket:
    print("Welcome to the event.")
else:
    print("Entry denied.")

This checks two conditions at once. The user must be at least 18 and must have a ticket No workaround needed..

Using Elif for Multiple Conditions

Sometimes, two outcomes are not enough. Python provides the elif keyword, short for “else if.” It allows you to test multiple conditions in order.

The syntax is:

if condition1:
    # code block 1
elif condition2:
    # code block 2
else:
    # code block 3

Example:

score = 72

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

In this example, Python checks each condition from top to bottom. Once it finds a true condition, it runs the matching block and skips the rest Not complicated — just consistent. No workaround needed..

If score is 72, the first condition is false, the second is false, and the third is true. So Python prints:

Grade: C

Using elif is very common when writing if

Nesting if‑else blocks

When a decision depends on more than one piece of information, you can place an entire if‑else statement inside another. The inner block runs only after the outer condition evaluates to True That's the part that actually makes a difference..

temperature = 5
is_raining = False

if temperature < 0:
    print("It's freezing.")
    if is_raining:
        print("And it's raining!And ")
    else:
        print("But the sky is clear. ")
else:
    print("The weather is tolerable.

In this snippet the outer test (`temperature < 0`) decides whether we even look at the rain condition. If the temperature is not below zero, the program skips the inner block entirely.

### The `else` clause can appear alone

If you want to execute a block when **any** of the preceding conditions fail, you can place an `else` without a matching `elif`. This is useful for a “fallback” case.

```python
command = "stop"

if command == "go":
    print("Moving forward.")
elif command == "pause":
    print("Temporarily halting.")
else:
    print("Unknown command.

Here the final `else` catches every value that isn’t `"go"` or `"pause"`.

### Ternary conditional expressions

Python lets you write a compact version of a simple if‑else on a single line:

```python
result = "adult" if age >= 18 else "minor"
print(result)

The expression after the if is evaluated only when the condition is True; otherwise the value after else is used. This form is handy for quick assignments but should be avoided when the logic becomes hard to read.

Common pitfalls and how to avoid them

Pitfall Why it matters Fix
Incorrect indentation Python uses indentation to delimit blocks. Now, Break the condition into separate variables or use parentheses to group parts. An assignment in a condition silently succeeds, often leading to unexpected flow. That's why a single space too few or too many will raise an IndentationError.
Forgetting the colon (:) The colon signals the start of a block; without it Python raises a SyntaxError. Double‑check every comparison operator.
Using = instead of == = assigns a value, while == tests equality.
Complex conditions in one line Long expressions can become unreadable, especially when mixing and/or. Always use a consistent number of spaces (PEP 8 recommends 4) and never mix tabs with spaces.
Deep nesting More than three levels of nesting can be confusing and hard to maintain. Refactor repeated logic into functions or use early returns to flatten the structure.

Best‑practice checklist

  1. Readable names – Use variables that describe the condition (is_adult, has_permission) rather than generic terms like a or b.
  2. Single responsibility – Keep each if block focused on one decision; if it grows, extract it into a helper function.
  3. Order matters – Place the most specific conditions first, the most general last. This prevents early exits from skipping needed checks.
  4. Avoid “magic numbers” – Define constants at the top of the file (MAJORITY_AGE = 18) and reference them in conditions.
  5. Test edge cases – Verify behavior when conditions are exactly on boundary values (age == 18, score == 60, etc.).

Putting it all together

MAX_SCORE = 100
MIN_PASS = 60
student_score = 77
has

Now let’s see how we can put everything together in a realistic scenario.  
We already defined `MAX_SCORE`, `MIN_PASS`, and the actual `student_score`. The next step is to determine whether the student has passed, needs improvement, or has failed, and then print an appropriate message.

```python
# Determine the outcome using a clear, readable structure
if student_score >= MIN_PASS:
    # The student cleared the bar – decide if they excelled
    if student_score == MAX_SCORE:
        result = "perfect score!"
    else:
        result = "passed."
elif student_score >= MIN_PASS // 2:          # e.g., 30 points is a “needs work” threshold
    result = "needs improvement."
else:
    result = "failed."

print(f"Student result: {result}")

A few notes about this block:

  • Constants are used (MAX_SCORE, MIN_PASS) so that the logic stays easy to adjust later.
  • Descriptive variable names (result) make the final output self‑documenting.
  • Early‑exit style isn’t needed here, but the nesting depth is limited to two levels, keeping the code readable.
  • If you prefer a more compact way to express the “perfect score” case, you could replace the inner if with a ternary expression:
result = (
    "perfect score!" if student_score == MAX_SCORE
    else "passed."
) if student_score >= MIN_PASS else (
    "needs improvement." if student_score >= MIN_PASS // 2
    else "failed."
)
print(f"Student result: {result}")

While this one‑liner captures the whole decision tree, it quickly becomes hard to follow. Use the multi‑line version for maintainability.

Bringing it all together

The examples above demonstrate how to:

  1. Structure conditionals with if, elif, and else for clear, linear logic.
  2. take advantage of ternary expressions for tiny, obvious transformations without sacrificing readability.
  3. Follow best‑practice checklists—meaningful names, single responsibility, ordered conditions, constants, and edge‑case testing.

By consistently applying these patterns, you’ll write code that not only works correctly but also reads like a well‑crafted story, making future maintenance and collaboration far smoother. Happy coding!

Just Hit the Blog

Latest and Greatest

You Might Find Useful

Topics That Connect

Thank you for reading about How To Write If Else In Python. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home