Conditional Statements
if / else and switch statements run code only when a condition is true.
Beginner
A conditional checks a Boolean expression and picks a branch:
temperature = 41
if temperature > 40:
print("Overheat — fan on")
elif temperature > 30:
print("Warm")
else:
print("Normal")
In C, C++ and Java, a switch statement selects among many constant values:
switch (command) {
case 'F': forward(); break;
case 'B': backward(); break;
default: stop();
}
Forgetting break in C causes fall-through into the next case — sometimes useful, usually a bug.
Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.
Discussion (0)
Sign in or join free to ask questions and discuss this topic.