Mojo If Else Conditions

Conditions let your program make decisions. Instead of running the same steps every time, your program evaluates a situation and chooses the appropriate path. Mojo's if-else structure gives you full control over branching logic.

The Decision Tree Concept

        Is temperature > 30°C?
              /        \
           Yes           No
           /               \
  "Wear sunscreen"     "Bring a jacket"

Every conditional in programming follows this same fork-in-the-road pattern. You ask a yes/no question, then follow the matching branch.

The Basic if Statement

An if statement runs a block of code only when its condition evaluates to True.

fn main():
    var temperature = 35

    if temperature > 30:
        print("It is hot outside.")
        print("Carry water.")

Output:

It is hot outside.
Carry water.

If temperature were 25, the condition 25 > 30 evaluates to False and neither print statement runs.

Adding else

The else block runs when the if condition is False. It is the fallback path.

fn main():
    var score = 45

    if score >= 50:
        print("You passed!")
    else:
        print("You did not pass.")
Flow Diagram:
  score = 45
      │
      ▼
  score >= 50?
  /          \
True         False
  │               │
"You passed!"   "You did not pass."

The elif Clause

Use elif (short for "else if") when you have more than two possible paths. Mojo checks each condition from top to bottom and runs the first block whose condition is True. The remaining branches are skipped.

fn main():
    var grade = 72

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

Output:

Grade: C
Evaluation Order:
  72 >= 90?  → False, skip
  72 >= 80?  → False, skip
  72 >= 70?  → True, run! → "Grade: C"
  (remaining elif and else never checked)

Nested Conditions

You can place an if statement inside another if block. This is called nesting. Use it to check secondary conditions that only matter when a primary condition is true.

fn main():
    var age = 20
    var has_id = True

    if age >= 18:
        if has_id:
            print("Entry allowed.")
        else:
            print("Show your ID to enter.")
    else:
        print("Under 18. Entry not allowed.")
Nested Flow:
  age >= 18?
  ├── True:
  │     has_id?
  │     ├── True  → "Entry allowed."
  │     └── False → "Show your ID."
  └── False → "Under 18. Entry not allowed."

Limit nesting to two or three levels deep. Deeper nesting makes code harder to read and debug.

Conditions with Logical Operators

Combine multiple checks in one condition using and, or, and not.

fn main():
    var speed = 85
    var is_raining = True

    # Speeding OR driving in rain → warn the driver
    if speed > 80 or is_raining:
        print("Slow down and drive carefully.")

    # Must meet both conditions for safe clearance
    if speed <= 80 and not is_raining:
        print("Conditions are safe.")
    else:
        print("Take extra caution.")

Checking Multiple Values with Ranges

Mojo lets you chain comparisons in a natural way that resembles mathematical notation.

fn main():
    var bmi = 22.5

    if 18.5 <= bmi < 25.0:
        print("Normal weight range")
    elif bmi < 18.5:
        print("Underweight")
    else:
        print("Overweight range")

The expression 18.5 <= bmi < 25.0 checks two conditions at once — it equals bmi >= 18.5 and bmi < 25.0. This mirrors the mathematical interval notation [18.5, 25.0) directly in code.

Ternary-Style Expressions

For simple two-outcome decisions, Mojo supports an inline conditional expression that fits on one line.

fn main():
    var x = 10
    var label = "positive" if x > 0 else "non-positive"
    print(label)   # positive
Pattern:  value_if_true  if  condition  else  value_if_false
Example:  "positive"     if  x > 0      else  "non-positive"

Use this only when both outcomes are simple values. Avoid it when the condition or outcomes are complex — a regular if-else block is clearer.

Common Beginner Mistakes

Using = Instead of ==

A single = assigns a value. A double == compares two values. Writing if x = 10: is an assignment, not a comparison, and Mojo will reject it with a compile error.

Forgetting the Colon

Every if, elif, and else line must end with a colon. Missing the colon produces a syntax error.

Misaligned Indentation

The body of each branch must be indented consistently. Mixing tabs and spaces, or indenting some lines by 2 spaces and others by 4, causes indentation errors.

Real-World Example: Traffic Light

fn main():
    var light = "yellow"

    if light == "green":
        print("Go")
    elif light == "yellow":
        print("Slow down")
    elif light == "red":
        print("Stop")
    else:
        print("Unknown signal — stop and check")

Output:

Slow down

Key Takeaways

The if block runs when its condition is True. The else block runs when the condition is False. The elif clause checks additional conditions in sequence. Nest conditionals to handle multi-level decisions, but keep nesting shallow. Use logical operators to combine multiple checks in one condition. Always use == for comparison and = for assignment.

Leave a Comment

Your email address will not be published. Required fields are marked *