Selection: if, elif and else
About this lesson: Selection: if, elif and else
In short
Selection lets a program choose a path. The condition after if is either True or False. If True, the indented lines run; if False, the else lines run instead. Try scores either side of 50.

What you'll explore
- Making decisions: if and else
- Selection lets a program choose a path. The condition after if is either True or False.
- More than two paths: elif for extra choices
- elif means 'else if'. Python checks each condition in order and runs only the FIRST one that is True, then skips the rest.
- Testing boundaries: The exact value where it changes
- Most selection bugs hide at the boundary. A pass mark of 50 must pass. Run the tests on this code, find the failing one, then fix the comparison.
- Combining conditions: and, or, not
- A ride needs riders aged at least 12 AND at least 140 cm tall. 'and' needs both conditions True; 'or' needs at least one.
- A real example: Ticket price calculator
- Children under 12 pay $5, people aged 65 or over pay $7, everyone else pays $12. Run it, then test the boundary ages 11, 12, 64 and 65.
- Check yourself: Which branch runs?
- x = 7 if x > 10: print("A") elif x > 5: print("B") else: print("C")
Also in this lesson
- Code to read
- Watch out for these
- Writing selection in tests
- Comparison operators
- More than the lesson
- Stretch your brain
- Code decisions
Words to know
- selection
- Choosing which code runs, depending on a condition.
- condition
- An expression that is either True or False.
- branch
- One of the paths a program can take.
- comparison operator
- ==, !=, <, <=, >, >=.
- Boolean operator
- and, or, not: combine or flip conditions.
- nested selection
- An if inside another if.
- indentation
- Spaces at the start of a line that show which block it belongs to.
- boundary data
- Test values at the edge of what is allowed.
- CASE statement
- Pseudocode for choosing between many fixed values.
- truth table
- A table showing the result for every combination of True and False.
Sources
- Python documentation: if statements; match statements
- BBC Bitesize, GCSE Computer Science: Selection
- MacTutor History of Mathematics: George Boole
- Isaac Computer Science: Selection and Boolean logic
← Binary addition, overflow and shifts · Text, images and sound as numbers →