Control flow: conditionals
Computer Science · Programming fundamentals
Question 1 of 10
0Which operator checks whether a value is greater than another?
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
Control flow: conditionals explained
A conditional statement runs a block of code only when a condition is true. The if statement is the basic form. Adding else gives an alternative path, and extra checks in the middle are written as elif in Python or else if in Java and JavaScript. Each condition is a Boolean expression, one that evaluates to true or false.
Conditions are built with comparison operators such as == (equal to), != (not equal), < and >=. They can be combined with and, or and not in Python, or with &&, || and ! in Java and JavaScript. The checks run in order, and only the first branch whose condition is true runs, so the order of the checks matters. An else branch with no condition acts as a default.
score = 62
if score >= 70:
grade = "A"
elif score >= 50:
grade = "B"
else:
grade = "C"
print(grade)
If the two checks were swapped, a score of 80 would match the ">= 50" test first and receive a B instead of an A. Ordering the checks from the highest threshold down avoids this kind of mistake.
Worked example
Trace the program above with score = 62.
- Is 62 >= 70? No, so skip the first branch.
- Is 62 >= 50? Yes, so set grade = "B" and skip the else branch.
- print(grade) displays B.
Changing the score to 45 would fail both checks and fall through to the else branch, giving C.
What you will practise
105 multiple-choice questions (Easy, Medium, Hard). Each answer is followed by an explanation.
Example questions
- Conditionals let programs:
- The if statement runs code when its condition is:
- The else clause runs when the if condition is:
- Nested conditionals are:
- A switch statement is useful for:
- A condition in a program is an expression that evaluates to:
- In an if / else if / else chain, which branch runs?
- The && operator returns true only when:
…and 97 more.