Python decisions and boundaries

Choose one branch with if, elif, and else.

Python
def grade(score):
    if score >= 80:
        return "Distinction"
    elif score >= 50:
        return "Pass"
    else:
        return "Retry"

print(grade(80))
print(grade(49))
assert grade(50) == "Pass"
Output
Distinction
Retry

Explanation

A conditional evaluates a Boolean condition. The first matching branch runs; later branches in the same chain are skipped.

Order overlapping ranges from the most specific to the broadest. Here a score of exactly 80 belongs to Distinction, while exactly 50 belongs to Pass.

Explore the dry run
Guided walkthroughReady
1def grade(score):
2 if score >= 80:
3 return "Distinction"
4 elif score >= 50:
5 return "Pass"
6 else:
7 return "Retry"
8
9print(grade(80))
10print(grade(49))
11assert grade(50) == "Pass"

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
Call grade with the boundary score 80.score = 80
—
80 >= 80 is true.condition = True
—
Return immediately from the function.result = Distinction
—
Print the first result.result = Distinction
Distinction
Call with 49; both threshold comparisons fail.score = 49
Distinction
Take the else branch.result = Retry
Distinction
Print the second result.result = Retry
Distinction
Retry
Check the lower pass boundary.result = Retry
Distinction
Retry

Cost and common mistakes

O(1) time and O(1) auxiliary space for a fixed number of branches.

  • Using > instead of >= changes boundary results.
  • This function assumes a numeric score; range validation can be added before classification.

Try it yourself

Add a valid range check for scores from 0 through 100.

Reveal answer and reasoning

Before the grade branches, reject score < 0 or score > 100. Check -1, 0, 100, and 101.

Further reading