Conditions
A condition is an expression that Python evaluates as true or false. An if block runs only when its condition is true. If it is false, Python checks elif branches in order and runs only the first matching branch; else handles the remaining case. Check boundary values when ranges meet, such as ages 12, 13, 17, and 18.
Use if, elif, and else in order: Python runs the first true branch and skips the rest. Compare values with ==, add colons, and indent each block.
Example check: Worked and guided code samples are checked against CPython 3.13. Practice uses Pyodide 0.29.5 (Python 3.13) in your browser. How we check lessons
Video lesson: Conditions
The preview is stored on this site. YouTube loads only when you press Play. Watch on YouTube
Jump to a chapter
Read the video transcript
Select a timestamp to watch that moment on YouTube.
- 00:00
Imagine a program that marks a quiz. A score of seventy-eight should receive Passed, but a score of ninety-five should receive Excellent. We could write a different program for each student, but conditions let one program choose its route from the data it receives. First, we will trace an if, elif, else chain carefully enough to predict its output before pressing Run. Then we will look at two decisions that seem similar but mean different things: combining requirements into one test, and running two independent tests. Along the way, we will fix the mistakes that make conditions fail even when the underlying idea is sound. Open the Conditions lesson on PythonLessonLab if you want to type each variation yourself.
- 00:44
You can pause after each prediction, run the code, and check whether your mental trace matched Python's. The goal is to understand why a branch runs, not merely memorize where the colon goes. Read the first line as an assignment: score now refers to the integer seventy-eight. The first test asks whether seventy-eight is at least ninety. It is false, so Python does not enter that indented body. The elif test asks whether seventy-eight is at least sixty. That is true, so Passed prints. The else body does not run. An if, elif, else chain selects the first matching route and then skips the rest.
- 01:24
Change the score to ninety-five. The first test is now true, so Excellent prints immediately, without testing the elif. Change it to forty, and both comparisons are false; Try again prints. Notice that greater than or equal includes the boundary itself. A score of exactly ninety counts as Excellent, and exactly sixty counts as Passed. Here is a useful challenge: what happens at one hundred? The current program says Excellent. If the new requirement is Perfect for exactly one hundred, put that precise test first. If you put it after score greater than or equal to ninety, the broad condition catches one hundred before Python reaches your new branch.
- 02:07
Branch order encodes a policy, so changing the order can change the answer even when the comparisons themselves stay the same. Now consider a workshop that admits someone who is at least eighteen years old or has a signed pass. With age seventeen and a pass, the age comparison is false and has_pass is true; false or true is true, so the program prints Admitted. Switch the pass to false and the fallback message prints. Replace or with and, and both requirements must be true. That is a different rule. Parentheses around the comparison make the intended grouping easy to read. Python can also test whether a collection has any items.
- 02:49
In the lesson's names example, the nonempty list makes if names true, and names at index zero is safe to read. An empty list makes the condition false, so we take the else route instead of causing an index error. Use that form only when you care whether anything is present; if you need at least two names, compare the length explicitly. Finally, picture an order with a member discount and a delivery fee. Starting from forty, the first independent if subtracts five and the second independent if adds three, leaving thirty-eight. Both rules apply. If the delivery rule were an elif, members would skip the fee entirely.
- 03:29
Use one if and elif chain for mutually exclusive outcomes; use separate if blocks when several effects can happen together. Before running, point to each condition and say its Boolean result aloud. That small habit makes complicated branches much easier to debug. The most visible syntax mistake is leaving the colon off an if or elif header. Python reports a SyntaxError near that header because it expected a colon before the branch body. Add the colon and run again. The next line must be indented, usually by four spaces. If it begins at the left edge, Python reports an IndentationError because it cannot tell which statements belong to the branch.
- 04:13
Those spaces are part of the program's structure. The quieter mistake is using a single equals sign to ask whether two values match. A single equals sign assigns a value; two equals signs compare values and produce True or False. For the Perfect branch, write score equals equals one hundred in the condition. Another quiet mistake is placing that precise branch after the broad ninety-or-more branch. The program runs and prints an answer, but it prints the wrong one for one hundred. That is why a successful run is not the end of testing. Try at least the boundaries, a typical value in the middle, and a value that should fall through to else.
- 04:56
For this score rule, test sixty, ninety, one hundred, and a failing score. Read the output as evidence about the rule you wrote, not proof that your intended rule was implemented. Your practical task is to add the exact-one-hundred branch before the ninety-or-more branch. Set score to one hundred and predict Perfect before you run it. Then try ninety-five, seventy-eight, and forty to confirm the other outcomes still work. Press Check Task on the lesson page after running your code. To stretch the idea, add a separate message for a score below zero. Ask yourself whether this is part of the same exclusive grading chain or an independent warning.
- 05:37
It belongs in the same chain if each score should have exactly one grade message. Pause and make that choice before changing the program. The quiz checks whether you understand skipped branches, the equality operator, and Boolean negation. If an answer surprises you, put that exact expression into the console and print its value. The strongest habit to take from this lesson is to predict first and then test. Once that feels natural, you are ready for loops, where a similar decision can be made repeatedly.
Understand the concept
A colon ends each branch header, and indentation marks the statements inside that branch. Use == to compare values; = assigns a value to a name.
- if, elif, and else
- Boolean comparisons
- Indented blocks
See it step by step
Read the code, predict the output, then compare it with the result.
01. Classify ages with ordered boundaries
age = 15
if age < 0:
print('Invalid age')
elif age < 13:
print('Child')
elif age < 18:
print('Teen')
else:
print('Adult')TeenFor age 15, the first two tests are false and age < 18 is true. Change age to 12, 13, 17, and 18 to check the boundaries; a negative age is rejected first.
02. Choose one branch
temperature = 30
if temperature >= 30:
print("Hot")
else:
print("Mild")HotThe condition is true, so Python runs the indented first branch and skips else.
03. Use elif
points = 75
if points >= 90:
print("Excellent")
elif points >= 60:
print("Passed")
else:
print("Try again")PassedPython checks the conditions in order. Only the first matching branch runs.
A closer look
Follow the reasoning, inspect each result, then try the suggested changes in the console below.
Combine rules without losing their meaning
Real decisions often depend on more than one fact. Imagine a workshop that admits adults, or younger learners who have a signed pass. The word or matters: either route is enough. Python evaluates each comparison to a Boolean value, then combines those values. Parentheses make the policy visible to the next person reading the code, even when operator precedence would produce the same answer.
With and, both requirements must hold; with or, one is sufficient. Python also short-circuits: it skips the right side of or when the left side is already true. This is useful when the second check would be expensive or unsafe. Predict the result if age becomes 17 and has_pass becomes False, then change those values in the console.
age = 17
has_pass = True
if (age >= 18) or has_pass:
print("Admitted")
else:
print("Ask for a signed pass")Admitted- age >= 18 is False; has_pass is True.
- or combines them into True, so only the first branch runs.
Empty data can be a useful condition
An if statement can test a collection directly. An empty list behaves as false; a list with at least one item behaves as true. This lets a program decide whether it has work to do without maintaining a second flag that could get out of sync. The same idea applies to empty strings, zero, and empty dictionaries, though their meanings in your program may differ.
Use a direct truth test when your question is simply 'is there anything here?' If you need a particular count, write a comparison such as len(items) >= 2 instead. A count and mere presence are different rules. Remove both names below and predict which message will print; then try a one-item list.
names = ["Maya", "Leo"]
if names:
print(f"First learner: {names[0]}")
else:
print("No learners yet")First learner: Maya- The list contains two values, so its truth value is True.
- The condition guards names[0]; indexing would fail on an empty list.
Choose between exclusive and independent checks
An if/elif chain chooses one route. Separate if statements ask separate questions and may run more than one body. That distinction matters for an order that can have both a discount and a delivery fee. If you used elif for the second rule, a qualifying discount would prevent the delivery rule from running even when both apply.
Write the rules in the form of the business decision. If categories truly exclude one another, an if/elif/else chain is clear; if two features can coexist, use independent checks. Below, the discount and delivery fee both affect the same total. Predict the total after changing is_member to False, and check it in the console.
total = 40
is_member = True
needs_delivery = True
if is_member:
total -= 5
if needs_delivery:
total += 3
print(f"Amount due: {total}")Amount due: 38- The first if reduces 40 to 35.
- The second if still runs and raises 35 to 38.
- An elif would incorrectly skip the fee for members.
Try it in Python
Edit the example and run it. Python starts in your browser the first time you click Run.
Python console
Ready to runNeed input()? Add one value per line
Your output appears here.
Need a hint?
Place if score == 100 first. Change the old if score >= 90 to elif score >= 90, keep the remaining elif and else, then test with score = 100.
Complete the task and select Check task to verify your code.
Quick quiz
Three questions. You can change your answers and try again.
Typical mistakes
Everyone meets these errors. See what causes them and how to fix them.
Missing colon
score = 75
if score >= 60
print("Passed")score = 75
if score >= 60:
print("Passed")What happens: SyntaxError on the if line.
End the if header with a colon.
Missing indentation
score = 75
if score >= 60:
print("Passed")score = 75
if score >= 60:
print("Passed")What happens: IndentationError after the if header.
Indent statements that belong to the branch.