When learning a new programming language, understanding how to control the flow of your code is essential. In Mojo, conditional statements and loops follow a familiar syntax for Python users, but with some key differences worth exploring. This article breaks down how to use if
, else
, elif
, for
, and while
in Mojo with clear examples.
1. Conditional Statements in Mojo
Mojo supports standard conditional structures like if
, elif
, and else
. Here’s a basic example:
fn check_number(x: Int):
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
2. The for Loop
The for
loop in Mojo allows you to iterate over ranges:
for i in range(0, 5):
print(i)
3. The while Loop
Use while
when the number of iterations isn’t known ahead of time:
var x = 5
while x > 0:
print(x)
x -= 1
4. Nested Logic and Indentation
Just like Python, indentation matters in Mojo. Here’s a nested example:
for i in range(0, 3):
if i % 2 == 0:
print(f"{i} is even")
else:
print(f"{i} is odd")
Conclusion
Control flow is at the heart of any program, and mastering it in Mojo opens the door to writing more dynamic and powerful code. Whether you’re running simple checks or building loops that power your app’s core logic, getting comfortable with these tools is a crucial step in your Mojo journey.
Comment