If-Else Statements
Swipe to show menu
As the Ninja game becomes more complex, you need to make choices instead of following a fixed path. In Python, these choices are made using if and else statements.
The if statement lets your code check a condition and act only when that condition is True. Think of it as asking a question: "Is this True?". If the answer is "Yes", the code runs.
if condition:
# Runs if condition is True
if ninja.object_right() == "wall":
ninja.go_up()
If there is the wall to the right, the Ninja moves one tile up. If there is no wall to the right, nothing happens.
Extending with else
Sometimes, doing nothing is not enough.
You may want the Ninja to take another action when the condition is False.
That is when you add else.
if condition:
# Runs if condition is True
else:
# Runs if condition is False
Combining if-else with a for Loop
if-else is especially useful when combined with loops, so the Ninja can decide what to do every time the loop
runs.
ninja.py
- The
forloop repeats the logic several times; - On each step, the Ninja checks what is in front of it;
- If there is a wall, the Ninja goes up, moves over it, and goes back down;
- If there is no wall, the Ninja simply moves right;
- Ninja picks up the sushi in the end.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat