What is an if statement?
In short
An if statement runs some code only when a condition is true, so a program can make decisions.
Without if statements, a program would do exactly the same thing every time. With them it can react: show a warning if the battery is low, let someone in if the password matches, give a discount if the basket is big enough.
An else part says what to do when the condition is false, and you can chain several checks to choose between more than two options.
Python
Choose between three messages
temperature = 25
if temperature > 30:
print("Hot")
elif temperature > 15:
print("Warm")
else:
print("Cold")Output
WarmJavaScript
The same idea in JavaScript
const temperature = 25;
if (temperature > 30) {
console.log("Hot");
} else if (temperature > 15) {
console.log("Warm");
} else {
console.log("Cold");
}Output
WarmLearn it properly
These free lessons teach it step by step, with questions and a program you write yourself.
- if and elseLearn Python →
- elif and Nested ConditionsLearn Python →
- if and elseLearn JavaScript →
- if and elseLearn C →
Try your first lesson free
Codiqo teaches coding in five-minute lessons with real code. Free on the web, iPhone and Android.