Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn If-Else Statements | If-Else Statements
Practice
Projects
Quizzes & Challenges
Quizzes
Challenges
/
Python Ninja

bookIf-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

ninja.py

copy
  • The for loop 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.
question mark

Which statements about if-else are True?

Select all correct answers

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 5. ChapterΒ 1

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

SectionΒ 5. ChapterΒ 1
some-alt