Conditional statements are the heart of programming languages. Mojo provides conditional logic using familiar keywords, if, elif, and else. These keywords allow your Mojo program to make decisions, control the flow of execution, and respond dynamically to different conditions.
What Are Conditional Statements in Mojo?
Conditional statements are used to execute certain blocks of code only when specific conditions are true. You can understand them as the brain of your program, which decides what to do based on different inputs or scenarios.
Mojo conditional statements include following three main keywords:
- if – This if keyword checks a condition and runs the block if it is True.
- elif – This is short for “else if”, which provides for multiple condition checks.
- else – This is the final condition because it runs a block when all the above conditions are False.
Basic Syntax of Mojo Conditionals
if condition:
# code block
elif another_condition:
# code block
else:
# code block
Indentation is important in Mojo, similar to Python. Remember, code blocks under each condition must be indented properly.
If you don’t know, what is “Indentation”, so learn the following basic definition about it:
Example Without Indentation (Wrong)
if age > 18:
print("You can vote")
Correct Indentation Example (Right)
if age > 18:
print("You can vote")
Why Use Conditional Statements?
Mojo conditional statements allow:
- Decision making in logic
- It can customize behavior based on user input
- Controlling loops, functions, and object behaviors
- Building AI and algorithmic flow
Example 1: Check if a Number is Positive, Negative, or Zero
This is beginner-friendly code, so you can use it in your IDE.
fn check_number(n: Int):
if n > 0:
print("The number is positive.")
elif n < 0:
print("The number is negative.")
else:
print("The number is zero.")
check_number(5)
check_number(-3)
check_number(0)
You can see, we have added three blocks and applied a specific condition to each. The function checks whether the given number is positive, negative, or zero. In between, we used an operator to compare the values.
Example 2: Decide Your Meal Based on Time
fn meal_by_hour(hour: Int):
if hour < 12:
print("It's time for breakfast.")
elif hour < 17:
print("It's time for lunch.")
elif hour < 21:
print("It's time for dinner.")
else:
print("It's too late for a heavy meal.")
meal_by_hour(10)
meal_by_hour(15)
meal_by_hour(19)
meal_by_hour(22)
Output:
meal_by_hour(10) # hour < 12 = It's time for breakfast.
meal_by_hour(15) # hour < 17 = It's time for lunch.
meal_by_hour(19) # hour < 21 = It's time for dinner.
meal_by_hour(22) # hour >= 21 all above failed = It's too late for a heavy meal.
- “elif” is used for multiple choice.
Example 3: Student Pass or Fail with Grading
fn evaluate_grade(score: Int):
if score >= 90:
print("Grade: A+")
elif score >= 75:
print("Grade: A")
elif score >= 60:
print("Grade: B")
elif score >= 40:
print("Grade: C")
else:
print("Fail")
evaluate_grade(95)
evaluate_grade(72)
evaluate_grade(39)
In this code, we have added multiple conditions to print all the grades according to marks. If you don’t know about the >= operator, first learn it from our course lists.
Nested Conditionals in Mojo
We can also place “if” inside another “if”. This is called nested conditionals.
fn nested_example(age: Int, has_id: Bool):
if age >= 18:
if has_id:
print("Entry allowed.")
else:
print("Please show your ID.")
else:
print("Entry denied.")
nested_example(20, True)
nested_example(20, False)
nested_example(16, True)
It is called nested conditionals in Mojo because we can use multiple conditions for each block of code. And avoid Indentation mistakes in nested code.
Above, all the examples are used for only reference purposes, but now we learn the real code project that is used in industries.
Real-Life Mini Project: Smart Water Tank Controller
fn main():
var water_level: Int = 55 # in percentage
var motor_status: String = ""
if water_level <= 25:
motor_status = "Motor ON - Water too low. Start filling."
elif water_level > 25 and water_level < 90:
motor_status = "Motor OFF - Water level is good."
else:
motor_status = "Motor OFF - Tank full! Please stop filling."
print("Water Level:", water_level, "%")
print("Action:", motor_status)
Output:
Water Level: 55 %
Action: Motor OFF - Water level is good.
Explanations of the code:
- water_level simulates sensor data (from 0 to 100).
- If the water level is ≤ 25%, it means very low, so we turn the motor ON.
- If the water level is between 25% and 90%, the tank is okay, so the motor remains OFF.
- If the water level reaches ≥ 90%, it’s almost full, so we ensure the motor is OFF and give a warning.
Now Challenge For Students In this Project
- Upgrade the project:
- Accept water level as user input.
- Add more levels of alert: low, medium, high.
- Store water level logs.
Do this by yourself without taking help from others.