Menu
Coddy logo textTech

If - Else

Part of the Fundamentals section of Coddy's R journey — lesson 23 of 78.

With a basic if statement, code either runs or it doesn't. But what if you want to do something different when the condition is false? That's where else comes in.

The else block provides an alternative path when the if condition evaluates to FALSE:

temperature <- 18

if (temperature > 30) {
  print("It's hot outside!")
} else {
  print("It's not too hot.")
}

In this example, since 18 is not greater than 30, R skips the first block and executes the else block instead, printing "It's not too hot."

This structure guarantees that exactly one of the two blocks will always run. Either the condition is true and the first block executes, or it's false and the else block executes:

score <- 75

if (score >= 60) {
  print("You passed!")
} else {
  print("Try again.")
}

Since 75 is greater than or equal to 60, this prints "You passed!" The else block is completely skipped.

challenge icon

Challenge

Easy

Use an if-else statement to print different messages based on whether a condition is true or false.

You are provided with the following variables:

age <- 16
required_age <- 18

Write an if-else statement that checks if age is greater than or equal to required_age.

  • If the condition is TRUE, print "Access granted"
  • If the condition is FALSE, print "Access denied"

Use the print() function for your output.

Cheat sheet

The else block provides an alternative path when the if condition is FALSE:

temperature <- 18

if (temperature > 30) {
  print("It's hot outside!")
} else {
  print("It's not too hot.")
}

This structure guarantees that exactly one of the two blocks will always run:

score <- 75

if (score >= 60) {
  print("You passed!")
} else {
  print("Try again.")
}

Try it yourself

# Variables provided
age <- 16
required_age <- 18

# TODO: Write your if-else statement below to check if age >= required_age
# Print "Access granted" if TRUE, "Access denied" if FALSE
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals