Python · Course navigation

Python decisions and boundaries

Choose one branch with if, elif, and else.

On this page
Before you start

Variables, comparison operators, and indentation.

  • Choose one branch with if, elif, and else.
  • Predict the sample output and explain the state changes.
  • Complete the practice task and check the boundary cases.

The concept

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.

Code example

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

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
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

Behind the scenes

How Python processes this code

Python runs this source through its interpreter. It creates objects for values and resolves names as each statement runs.

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