Learn

We’ve learned to use if statements to perform an action when a condition is met.

But what if we want something to happen when the condition is met, and something else to happen when the condition is not met? Else statements can be added to if statements.

If (condition) { Action to perform if the condition is met } else { Action to perform if condition is not met }

Imagine we are trying to go to the movies.

If (I have a car) { Drive to the theater } else { Walk to the theater } Watch movie.

Here our code would have us drive if we have a car, or walk if we don’t. We get there one way or another, then watch the movie.

Else statements help us define different paths for our code to follow. Let’s practice getting Codey to their goal using if and else statements.

Instructions

Here Codey will need to go in one direction before getting the key, and then another afterwards. Can you use an if/else statement to define that behavior?

Hint
Codey needs to go up if they don't have the key, and to go right if they do.
Solution
While program is running If Codey does not have key Move up Else Move right

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?