Back to Engineering
8 MAY 2026

If-Else Statements: Teaching Your Code to Make Decisions

CA
Compiled by Cypher Async

If-Else Statements: Teaching Your Code to Make Decisions

Life is full of decisions. "If it is raining, I will carry an umbrella. Otherwise, I will leave it at home." Your code needs to make decisions too — and if-else statements are exactly how it does that.


What Is an If-Else Statement?

An if-else statement is a control flow structure that lets your program execute different code depending on whether a condition is True or False.

Real-world analogy:

  Is it raining?
  ┌─────────────────────┐
  │  IF it is raining   │──── YES ──►  Pick up umbrella
  │  ELSE               │──── NO  ──►  Leave umbrella home
  └─────────────────────┘

The program checks the condition and takes one of two paths. Only one path is executed — never both.


Basic Syntax

Python:

if condition:
    # code to run if condition is True
else:
    # code to run if condition is False

Simple example:

temperature = 38

if temperature > 35:
    print("It is very hot today!")
else:
    print("The weather is pleasant.")

Output:

It is very hot today!

Because 38 > 35 is True, the if block runs. The else block is skipped.


How the Decision Works — Flowchart

  START
    │
    ▼
  Evaluate condition: temperature > 35
    │
    ├─── TRUE  ──►  Print "It is very hot today!"
    │                       │
    └─── FALSE ──►  Print "The weather is pleasant."
                            │
                            ▼
                          END

Comparison Operators

Conditions are built using comparison operators that return either True or False:

  OPERATOR   MEANING                  EXAMPLE         RESULT
  ────────   ──────────────────────   ─────────────   ──────
  ==         Is equal to              5 == 5          True
  !=         Is not equal to          5 != 3          True
  >          Greater than             10 > 7          True
  <          Less than                3 < 1           False
  >=         Greater than or equal    5 >= 5          True
  <=         Less than or equal       4 <= 3          False

Important: == checks equality, = assigns a value. They are different!


The elif Clause — More Than Two Paths

What if you have more than two possible outcomes? Use elif (short for "else if") to add extra conditions:

marks = 72

if marks >= 90:
    grade = "A+"
elif marks >= 75:
    grade = "A"
elif marks >= 60:
    grade = "B"
elif marks >= 40:
    grade = "C"
else:
    grade = "F"

print("Your grade is: " + grade)
# Output: Your grade is: B

Multi-path flowchart:

  START → marks = 72
    │
    ▼
  marks >= 90?  ── TRUE ──►  grade = "A+"  ──► END
    │
   FALSE
    │
    ▼
  marks >= 75?  ── TRUE ──►  grade = "A"   ──► END
    │
   FALSE
    │
    ▼
  marks >= 60?  ── TRUE ──►  grade = "B"   ──► END  ◄ (72 falls here)
    │
   FALSE
    │
    ▼
  marks >= 40?  ── TRUE ──►  grade = "C"   ──► END
    │
   FALSE
    │
    ▼
  grade = "F"   ──────────────────────────────► END

The program checks each condition from top to bottom and stops at the first one that is True.


Logical Operators — Combining Conditions

Sometimes one condition is not enough. You can combine them with and, or, and not:

and — Both conditions must be True

age = 22
has_id = True

if age >= 18 and has_id:
    print("Entry allowed.")
else:
    print("Entry denied.")
# Output: Entry allowed.

or — At least one condition must be True

is_weekend = False
is_holiday = True

if is_weekend or is_holiday:
    print("School is closed!")
else:
    print("Come to school.")
# Output: School is closed!

not — Reverses the condition

is_raining = False

if not is_raining:
    print("Great day for a walk!")
# Output: Great day for a walk!

Truth table for and and or:

  A       B       A and B     A or B
  ─────   ─────   ─────────   ──────
  True    True    True        True
  True    False   False       True
  False   True    False       True
  False   False   False       False

Nested If-Else — Decisions Inside Decisions

You can place an if-else inside another if-else:

is_member = True
cart_total = 1500

if is_member:
    if cart_total >= 1000:
        discount = 20
    else:
        discount = 10
else:
    discount = 0

print("Your discount is: " + str(discount) + "%")
# Output: Your discount is: 20%

Nested flowchart:

  Is member?
  ├── YES ──► Cart >= 1000?
  │           ├── YES ──► 20% discount
  │           └── NO  ──► 10% discount
  └── NO  ──► 0% discount

Keep nesting shallow (ideally no more than 2–3 levels). Deep nesting becomes very hard to read.


The Ternary / Inline If (One-liner)

For simple conditions you can write a compact one-liner:

Python:

age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)   # Output: Adult

JavaScript:

let age = 20;
let status = age >= 18 ? "Adult" : "Minor";
console.log(status);   // Output: Adult

Use these only for simple, readable cases — not for complex logic.


Common Beginner Mistakes

| Mistake | Example | Fix | |----------------------------------|-------------------------------|--------------------------------| | Using = instead of == | if score = 90: | if score == 90: | | Missing colon in Python | if score > 50 | if score > 50: | | Wrong indentation in Python | Code at wrong indent level | Align body under the if | | Checking string with == wrong | if name == Riya: | if name == "Riya": | | Forgetting else coverage | No fallback when all are False| Always add a final else |


A Complete Program: Traffic Light Logic

signal = "yellow"

if signal == "green":
    print("Go — the road is clear.")
elif signal == "yellow":
    print("Slow down — light is about to turn red.")
elif signal == "red":
    print("Stop — wait for the green light.")
else:
    print("Unknown signal — proceed with caution.")

Output:

Slow down — light is about to turn red.

Summary

| Keyword | Purpose | |---------|-------------------------------------------------| | if | Checks the first condition | | elif | Checks the next condition if the previous was False | | else | Runs if none of the above conditions were True | | and | Both conditions must be True | | or | At least one condition must be True | | not | Reverses the boolean value |

  • Every if can stand alone, but elif and else must follow an if
  • Conditions are evaluated top-to-bottom and stop at the first True
  • Avoid deeply nested if-else blocks — flatten them where possible
  • Always handle the default case with else

Decision-making is what makes programs useful. A program that always does the same thing regardless of input is just a fixed script. The moment you add an if-else, your code becomes intelligent — it can react to the world around it.


Published by Cypher Async — Agartala's offline coding school, building real engineers one concept at a time.