Core programming fundamentals · Lesson 9 of 60 · Code lesson, JavaScript or Python · Optional
Conditional statements
A condition is a check with a true or false answer, such as temperature > 20 (greater than 20).
if runs a block when its check is true, else if tries another check, and else runs when nothing matched.
A switch picks one path by comparing a value with several exact options.
Worked example
In JavaScript, else if adds another check, and a switch statement compares a value with several case labels.
const temperature = 10;
if (temperature > 20) {
console.log("Warm");
} else {
console.log("Cool");
}Output: Cool
In Python, elif adds another check, and the indented lines under each check belong to it.
temperature = 10
if temperature > 20:
print("Warm")
else:
print("Cool")Output: Cool
Your turn
Add one more check so a temperature above 30 prints Hot. Above 20 still prints Warm, and everything else prints Cool.
Your program is checked with these 3 inputs:
Input:
35
Expected output:
Hot
Input:
25
Expected output:
Warm
Input:
10
Expected output:
Cool
Loading your practice…
Preparing your workspace…