Beginner level · Module 2: Decisions and Loops · Lesson 1 of 3
Conditions with if, elif and else
Write programs that take different actions depending on the data, such as grading a score or applying a discount.
In this lesson you will
- Build conditions with ==, !=, <, >, and, or, not
- Order elif branches correctly
Key concepts
boolean expressionelif chainindentation block
The lesson
Programs make decisions with if statements. A condition is an expression that is either True or False, built with comparison operators such as >=, <, == (equal) and != (not equal). The indented block under the if runs only when the condition is True.
When there are several possible outcomes, chain them with elif and finish with else. Python checks the conditions from the top and runs only the first block whose condition is True, so the order matters: check the highest grade band first, then the next, and so on.
Combine conditions with and, or and not — for example, attendance >= 80 and score >= 50. Always test the boundaries: if the pass mark is 50, test 49, 50 and 51.
Step by step
- Write the grade bands down before coding.
- Convert the typed score to a number.
- Write if/elif/else blocks from the highest band to the lowest.
- Test with 0, 49, 50, 80 and 100 and compare with your expected grades.
Practice activity
Write a grading script that converts an exam score (0–100) into a grade A–F using the grading bands provided by the instructor.
Expected result: Your grading script returns the correct grade for boundary values such as 49, 50 and 80.
Check your understanding
-
If several elif conditions are True, which branch runs?
Show answer
Only the first True branch from the top.
-
Write a condition that is True when age is between 18 and 35 inclusive.
Show answer
18 <= age <= 35 (or age >= 18 and age <= 35)
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.