LEARN PYTHON | Selection: If, Elif And Else

Lesson objective

Use indented if, elif and else branches, distinguish one selection chain from independent tests, and choose a branch order matching the requirement.

Learn

02.2 | SELECTION: IF, ELIF AND ELSE

01 | MAKE ONE DECISION

A program can now calculate a condition, but printing True is not always the useful response. Selection lets the program execute a group of instructions only when a condition holds.

An if statement begins with if, then a condition and a colon. The indented lines underneath form its body, the instruction group controlled by that if.

If the condition is true, the body runs. If it is false and there is no alternative branch, the body is skipped. Execution then continues with the following unindented statement.

score = 12
if score >= 10:
    print("Target reached")
print("Check complete")

EXPECTED OUTPUT

Target reached
Check complete

02 | INDENTATION IS PART OF PYTHON’S MEANING

Indentation is not only visual layout: it defines which statements belong to a block. Use four spaces per level as the standard beginner convention, and keep the editor set to spaces.

A colon introduces the block. Lines at the same indentation level belong to the same group. Reducing the indentation ends that group. Missing indentation can raise IndentationError; inconsistent tabs and spaces can cause related problems.

Compare a message inside if with one after it. A congratulation belongs to the selected route; a closing message might belong outside so it runs whichever route was taken.

score = 7
if score >= 10:
    print("Target reached")
    print("Collect your badge")
print("Thank you for taking part")

EXPECTED OUTPUT

Thank you for taking part

03 | ELSE SUPPLIES THE ALTERNATIVE

else follows its if at the same indentation level and has a colon but no condition. It runs when that if condition is false.

In an if/else pair, one body is selected during that evaluation. The false route is not an error; it can be the ordinary outcome of a valid condition.

score = 7
if score >= 10:
    print("Target reached")
else:
    print("Keep practising")
print("Check complete")

EXPECTED OUTPUT

Keep practising
Check complete

04 | ELIF ADDS ANOTHER TEST

elif means else if. Python reaches its condition only if the preceding conditions in that chain were false. When a condition is true, that branch runs and the remaining elif and else branches are skipped.

For mutually exclusive score bands, check the highest band first. A score of 85 meets both “at least 80” and “at least 50”, but this chain selects the first matching branch, Distinction.

Assume a valid score from zero to one hundred for this banding example. Range validation is a separate requirement.

score = 85
if score >= 80:
    print("Distinction")
elif score >= 50:
    print("Pass")
else:
    print("Not a pass")

EXPECTED OUTPUT

Distinction

05 | BRANCH ORDER CAN HIDE A RESULT

If the first condition were score >= 50, every distinction-level score would enter that branch. A later elif score >= 80 would never be reached for those values.

A condition being mathematically true does not mean Python evaluates it. After a selected branch, the rest of that chain is skipped. In a trace table, record “not tested” for an unreached condition rather than incorrectly calling it False.

Test 49, 50, 79 and 80 to check the changeover points. Add a typical interior score such as 65. Expected outputs should be written before running.

06 | INDEPENDENT IFS ARE A DIFFERENT RULE

Two separate if statements can both run. That is useful when several independent notices may apply, such as a high score and a perfect attendance badge.

It is often wrong for exclusive categories. Two independent tests score >= 50 and score >= 80 both print messages at 85, rather than choosing one category.

Use a chain when only one route should apply. Use independent tests when each condition deserves its own decision. The syntax should follow the intended behaviour.

score = 85
if score >= 50:
    print("Pass threshold reached")
if score >= 80:
    print("Distinction threshold reached")

EXPECTED OUTPUT

Pass threshold reached
Distinction threshold reached

07 | COMBINE CONDITIONS WHEN ONE RULE NEEDS THEM

An if condition can contain and, or and not. If entry requires a paid ticket and available space, both must be true in the same condition.

Choose a message that tells the user what happened, but avoid claiming which individual condition failed when the combined false result does not distinguish them. More specific messages need additional tests.

paid = True
space_available = False
if paid and space_available:
    print("Entry allowed")
else:
    print("The entry requirements are not all met")

08 | NEST A DECISION ONLY WHEN NEEDED

A nested if lies inside another branch. Python reaches it only when that containing branch is selected. This can distinguish successive reasons without testing an irrelevant stage.

Here, an unpaid user never reaches the space test. A paid user receives a space-specific response. The inner else belongs to the inner if because their indentation matches; the outer else belongs to the outer if.

paid = True
space_available = False
if paid:
    if space_available:
        print("Entry allowed")
    else:
        print("No space available")
else:
    print("A paid ticket is required")

EXPECTED OUTPUT

No space available

09 | TRACE THE SCORE CHAIN

Choose an INTEGER score from zero to one hundred. Predict which tests are reached and which one message appears. The activity models the fixed chain below.

if score >= 80:
    print("Distinction")
elif score >= 50:
    print("Pass")
else:
    print("Not a pass")

    10 | CHECK A RANGE BEFORE CLASSIFYING

    A program can reject an invalid score before applying bands. The first condition checks whether the value is outside zero to one hundred. Its true branch reports invalid input; otherwise the chain moves to the valid score categories.

    This validates the range after int conversion. A word such as eighty still raises ValueError before the condition runs. Handling non-numeric input will be introduced in the debugging lesson.

    score = int(input("Score from 0 to 100: "))
    if score < 0 or score > 100:
        print("Score out of range")
    elif score >= 80:
        print("Distinction")
    elif score >= 50:
        print("Pass")
    else:
        print("Not a pass")

    11 | WRITE A POSITIVE, NEGATIVE OR ZERO REPORT

    Ask for an INTEGER. Use one chain to report positive, negative or zero. These categories are exclusive and cover every integer, so only one message should appear.

    Test -1, 0 and 1, plus larger values. Explain why zero is not positive or negative. Use a label and clear wording rather than only printing a Boolean result.

    Extension: add a separate independent even-number notice using number % 2 == 0. Explain why that second if is independent: a number can be positive and even simultaneously.

    PUT YOUR SKILLS TO WORK

    Use the Section 2 challenges to practise these ideas independently. Work in your Python editor, predict results and keep a short test record.

    Section 2 challenges Python course navigation

    MATCH THE PYTHON TERM TO ITS MEANING

    Terminology

    Terminology

    Selection

    Choosing which instruction group executes.

    if

    Introduces a conditional branch.

    elif

    A further condition reached if earlier chain conditions fail.

    else

    The alternative when earlier chain conditions fail.

    Branch

    One possible instruction route.

    Body

    The instruction group belonging to a control statement.

    Block

    A group of statements defined by indentation.

    Colon

    Introduces an indented block here.

    Indentation

    Leading spacing that defines Python block structure.

    Dedent

    Return to a lower indentation level.

    Chain

    One if with its associated elif and else branches.

    First match

    Only the first true branch in a chain executes.

    Independent if

    A separate decision that may run alongside another.

    Nested if

    An if located inside another block.

    Not tested

    A condition was not reached, rather than evaluated false.

    Branch order

    The order in which chain conditions are considered.

    Range validation

    Checking a value against permitted bounds.

    IndentationError

    An error in the structure of indented code.

    Questions

    Questions

    CHECK YOUR UNDERSTANDING

    Select all correct choices. Each exact set earns one point.

    1. Which belong to Python if syntax?
    2. Which describe else?
    3. Which describe an if/elif chain?
    4. At score 80, which fit the high-first chain?
    5. Which explain indentation?
    6. Which describe independent ifs?
    7. Which describe a nested if?
    8. Which score tests check changeovers?

    EXPLAIN AND COMPARE

    Write your answers before revealing each sample.

    1. Explain the if body.

    2. Describe else syntax and purpose.

    3. Explain why high-first score order matters.

    4. Compare a chain with independent ifs.

    5. Explain not tested versus False.

    6. Describe how indentation pairs else with if.

    7. Write an outside-range score check.

    8. Suggest tests for positive/negative/zero selection.

    CODE IT | YOUR INDEPENDENT CHALLENGE

    Build a positive, negative or zero report with one selection chain, then add an independent even-number notice.

    Work in your Python editor. Keep a working version, explain one design choice and record at least two tests. Use the Learn tab for worked examples before comparing your result.

    Flashcards

    Flashcards

    Click to flip. Select the ideas you need to revisit.

    0 cards selected for revision.

      Selections are kept while this page is open.

      Workbook

      Workbook

      COMING SOON

      The workbook for Selection: If, Elif And Else is coming soon. Complete the matching task and written questions in your exercise book.