MGU Computer Science Series — Programming with Python
Part II: Control Flow and Program Logic
Conditions · Branches · Decisions · Tracing
Chapter 6 of 30
6
MGU Computer Science Series  ·  Programming with Python  ·  Library Textbook Edition

Chapter 6:
If, Elif, and Else

Teaching programs to make decisions — conditional execution, branching logic, nested decisions, and the discipline of tracing exactly which path a program takes

■ Part II of VII ■

■ 10 Sections  •  Chapter 6 of 30 ■

Builds directly on Chapter 5 — Booleans, Comparisons, and Decisions

Chapter Purpose and Learning Objectives

Chapter 5 gave you the tools to build conditions: Boolean values, comparison operators, logical operators, and compound expressions. You learned how Python evaluates whether something is True or False. Now you need to use those conditions to control what your program actually does.

This chapter teaches conditional execution — the ability to run different code depending on whether a condition is true or false. Every real program needs this ability. A password check needs it. A grade calculator needs it. A game menu needs it. An eligibility form needs it.

By the end of this chapter, you will be able to write if statements, else branches, and elif chains. You will trace which branch executes for a given input. You will recognize common mistakes in branching logic and you will design clear, correct conditional programs.

Opening Question

A vending machine dispenses an item only if you have inserted enough money. A library charges a late fee only if a book is overdue. A login screen shows an error only if the password is wrong. What do these situations have in common? Each one depends on a condition that determines which of two or more outcomes occurs. This chapter teaches you how to express exactly that kind of logic in Python — precisely, correctly, and in a way you can trace step by step.

10Sections
10Key Terms
6Tasks
30Total Chapters

Learning Objectives

By the end of this chapter, you should be able to:

  1. 1Explain what conditional execution is and why programs need it.
  2. 2Write a correct if statement, including the condition, colon, and indented block.
  3. 3Explain how Python uses indentation to define code blocks, and identify common indentation mistakes.
  4. 4Write an if/else statement and explain why exactly one branch always runs.
  5. 5Write an elif chain to handle more than two mutually exclusive cases.
  6. 6Distinguish between mutually exclusive elif chains and independent, separate if statements.
  7. 7Write and trace nested decisions, and know when nesting is preferable to a compound condition.
  8. 8Design branching logic by identifying all cases, checking for mutual exclusivity, ordering conditions correctly, and including a default case.
  9. 9Trace a conditional program by hand, including with a tracing table, and predict its output.
  10. 10Identify and correct common conditional logic errors, including dead code, missing colons, bad indentation, and wrong operator use.

Sections at a Glance

Sections 6.1 – 6.3
The Basic Branch: Conditions, Structure, and Indentation
Conditional Execution · The if Statement · Code Blocks

Conditional Execution

Most of the programs you have written so far run every line, every time. Line 1 runs. Then line 2. Then line 3. The order is fixed, and every line executes.

Real programs do not work that way. A real program needs to ask: Is this condition true right now? And based on the answer, it takes one path or a different path. This is called conditional execution: some code runs only when a condition is satisfied.

You already see conditional logic everywhere in everyday life.

  • A vending machine dispenses an item only if you have put in enough money.
  • A school library charges a late fee only if a book is overdue.
  • A ride-share app shows a driver's rating only if at least one rating exists.
  • A website shows an error message only if the login fails.

In every case, something happens under one condition and something else happens (or nothing happens) under a different condition. Python gives you a direct way to write this kind of logic. It is called an if statement.

Study Note

Conditional execution is not just about if statements. It is a way of thinking about programs. Before you write a single line of code, ask: What decisions does this program make? What are the possible paths? What condition separates one path from another? What should happen in each case? Asking these questions before writing code is one of the habits that separates programmers who struggle from programmers who succeed.

The Structure of an if Statement

The simplest conditional in Python is an if statement with one branch.

if condition: statement

Read that pattern carefully. There are four things to notice.

Part 1
The keyword if
Python recognizes if as the start of a conditional statement. It must be lowercase. If and IF are not valid.
Part 2
The condition
Any expression that evaluates to True or False. Usually a comparison or logical expression, exactly like those you practiced in Chapter 5.
Part 3
The colon
The colon : appears at the end of the if line. It is required. Forgetting it is one of the most common beginner errors.
Part 4
The indented block
The lines underneath the if line are indented. They run only when the condition is True. If the condition is False, they are skipped entirely.

Here is a complete, concrete example:

temperature = 35 if temperature > 30: print("It is hot outside.")

When Python runs this program, it evaluates the condition temperature > 30. Since temperature is 35, the condition is True. Python runs the indented line and prints:

It is hot outside.

Now change the value:

temperature = 20 if temperature > 30: print("It is hot outside.")

Now the condition temperature > 30 evaluates to False. Python skips the indented line. The program runs and produces no output. That is conditional execution. The print() call only happens when the condition is satisfied.

The indented block can contain more than one line. Every indented line is part of the block.

temperature = 35 if temperature > 30: print("It is hot outside.") print("Consider wearing light clothing.") print("Stay hydrated.")

All three print() calls are inside the block. All three run if the condition is True. All three are skipped if the condition is False.

Indentation and Code Blocks

Python uses indentation to define which lines belong to a block. This is not optional and it is not decorative. Indentation is part of Python's syntax.

In most programming languages, blocks are marked with braces {} or keywords like begin and end. Python instead uses indentation. The amount of indentation must be consistent within a block. The standard in Python is four spaces.

score = 85 if score >= 60: print("You passed.") print("Well done.") print("The program has finished.")

Trace this carefully. The first two print() calls are indented by four spaces. They belong to the if block and only run when score >= 60. The last print() call is not indented. It is back at the left margin, which means it is outside the if block. It runs regardless of the condition.

With score = 85, the output is:

You passed. Well done. The program has finished.

If you change score to 45:

The program has finished.

Only the unindented line runs. The block is skipped.

Common Indentation Mistakes

Mixing tabs and spaces. Python 3 does not allow mixing them. Use four spaces consistently; your editor should handle this automatically.

Inconsistent indentation within a block. If one line is indented four spaces and the next is indented five, Python raises an IndentationError.

Forgetting to indent at all. If the line after an if is not indented, Python raises an IndentationError.

Indenting when you should not. If you indent a line that should be outside the block, it will only run when the condition is true — which is probably not what you wanted.

Read your indentation carefully. Indentation errors are among the easiest mistakes to fix once you spot them, but they can be hard to see at first because you are reading meaning, not whitespace.

Sections 6.4 – 6.6
More Branches: Else, Elif, and Mutual Exclusivity
Two-Way Decisions · Multi-Way Decisions · Independent Conditions

else Statements

An if statement with no else creates a single optional branch. The block either runs or it does not, and in either case the program continues.

But many decisions have two sides. Either the condition is true and something happens, or the condition is false and something different happens. For this, Python provides the else clause.

if condition: # runs when condition is True else: # runs when condition is False

The else keyword is followed by a colon and an indented block, exactly like if. The else block runs only when the if condition is False. Exactly one of the two blocks always runs. They are mutually exclusive.

age = 16 if age >= 18: print("You are eligible to vote.") else: print("You are not yet eligible to vote.")

With age = 16, the condition age >= 18 is False. The else block runs:

You are not yet eligible to vote.

Change age to 20:

You are eligible to vote.

The if block runs, and the else block is skipped. Notice that the program always produces output. Whether the condition is true or false, one of the branches runs. That is the point of else: it ensures that something happens in every case.

Example 6.4.1
Checking a password
entered_password = "sunshine" correct_password = "p@ssw0rd" if entered_password == correct_password: print("Access granted.") else: print("Incorrect password. Please try again.")
  • Conditionentered_password == correct_password compares the two strings, which are not equal, so the condition is False.
  • Branch takenThe else branch runs, printing "Incorrect password. Please try again."
  • PatternThis kind of two-branch structure — success on one side, failure on the other — appears constantly in real programs.

elif for Multiple Cases

if and else handle two cases: the condition is true, or the condition is false. But many real decisions involve more than two cases. Consider assigning a letter grade:

Score RangeLetter Grade
90 or aboveA
80 to 89B
70 to 79C
60 to 69D
Below 60F

That is five distinct cases. You cannot handle five cases with just if and else. You need a way to check a series of conditions in order. Python provides elif, which stands for else if. An elif clause adds another condition to test if the previous conditions were all false.

if first_condition: # runs if first_condition is True elif second_condition: # runs if first_condition is False AND second_condition is True elif third_condition: # runs if first and second were False AND third_condition is True else: # runs if all conditions above were False

Python evaluates the conditions from top to bottom. As soon as one condition is True, its block runs and the rest of the chain is skipped entirely. If no condition is true, the else block runs (if there is one). Here is the grade example:

score = 83 if score >= 90: print("Grade: A") elif score >= 80: print("Grade: B") elif score >= 70: print("Grade: C") elif score >= 60: print("Grade: D") else: print("Grade: F")

With score = 83, Python evaluates the conditions in order: score >= 90 → 83 >= 90 → False, move on. score >= 80 → 83 >= 80 → True. Run this block and stop.

Grade: B

None of the remaining elif or else branches are evaluated. The chain stops as soon as one match is found.

Why Order Matters

Consider what happens if you reverse the order:

score = 83 if score >= 60: print("Grade: D") elif score >= 70: print("Grade: C") elif score >= 80: print("Grade: B") elif score >= 90: print("Grade: A") else: print("Grade: F")

With score = 83, Python evaluates the first condition: 83 >= 60. That is True. So it prints Grade: D and stops. The student with an 83 is incorrectly assigned a D. This happens because elif chains stop at the first true condition. When the conditions overlap — as they do here — the order completely determines the result. Always arrange conditions from most specific (or highest threshold) to least specific, or think carefully about what each condition covers.

A Chain With No else

You do not always need an else. If no condition is met and there is no else, nothing happens.

temperature = 22 if temperature > 35: print("Extreme heat warning.") elif temperature > 30: print("Hot day. Stay cool.") elif temperature > 25: print("Warm day.")

With temperature = 22, none of the conditions are true and there is no else. The program produces no output. This is sometimes what you want: only act if a notable condition occurs.

Mutually Exclusive Conditions

When you use if, elif, and else together, exactly one branch executes per run. The conditions are mutually exclusive within a chain: Python guarantees that once one branch runs, the rest are ignored. This is different from writing separate if statements.

Program A — elif chainProgram B — separate if statements
score = 95 if score >= 90: print("Excellent") elif score >= 80: print("Good") elif score >= 70: print("Satisfactory") score = 95 if score >= 90: print("Excellent") if score >= 80: print("Good") if score >= 70: print("Satisfactory")

With score = 95, Program A prints only Excellent because the chain stops after the first true condition. Program B prints all three, because each if is independent and Python evaluates all three conditions:

Excellent Good Satisfactory

This is one of the most important structural decisions in conditional programming. Ask yourself: should exactly one thing happen, or can multiple things happen? Use elif chains for mutually exclusive cases. Use separate if statements when multiple conditions can independently apply.

Example 6.6.1
Separate if statements used correctly
message = "Hello, world!" if "Hello" in message: print("Contains a greeting.") if len(message) > 10: print("Message is long.") if "!" in message: print("Message ends with excitement.")
Contains a greeting. Message is long. Message ends with excitement.

All three conditions can be independently true, so separate if statements are appropriate here.

Sections 6.7 – 6.10
Designing and Verifying Conditional Programs
Nested Decisions · Design Habits · Tracing · Common Errors

Nested Decisions

Sometimes a decision depends on a previous decision. After Python takes one branch, you might need to make another choice inside that branch. This is called a nested decision: one if statement appears inside the block of another.

age = 20 has_ticket = True if age >= 18: if has_ticket: print("Welcome. Enjoy the event.") else: print("You need a ticket to enter.") else: print("Sorry, this event is for adults only.")

Trace this step by step. Python evaluates the outer condition: age >= 18. With age = 20, this is True. Python enters the outer block. Inside the outer block, Python evaluates the inner condition: has_ticket. Since has_ticket is True, Python runs the inner if block.

Welcome. Enjoy the event.

Now try age = 20 and has_ticket = False: the outer condition 20 >= 18 is True, so Python enters the outer block; the inner condition is False, so Python skips the inner if and runs the inner else.

You need a ticket to enter.

Now try age = 15 and has_ticket = True: the outer condition 15 >= 18 is False, so Python runs the outer else.

Sorry, this event is for adults only.

Notice that the inner if block is never even reached when the outer condition is false. Python does not evaluate the inner condition because it is inside a block that did not run.

Nesting Adds Indentation Layers

Each nested level adds four more spaces. Deep nesting — three or more levels — makes code hard to read. If you find yourself writing deeply nested conditionals, it is often a sign that the logic can be restructured.

Nested Decisions Versus Compound Conditions

Sometimes nesting can be replaced with a compound condition. Compare:

Nested versionCompound condition version
if age >= 18: if has_ticket: print("Welcome.") if age >= 18 and has_ticket: print("Welcome.")

Both do the same thing. The compound version is shorter and often clearer when the logic is simple. Nesting is more appropriate when the two decisions have different consequences — when you need separate else branches for each level.

Designing Clear Branching Logic

Writing a conditional statement that technically works is not enough. The goal is to write conditional logic that is correct, readable, and easy to verify. Here are the key questions to ask when designing branching logic.

Question 1
What are all the possible cases?
List every case the program needs to handle before writing code. If you miss a case, your program will silently do nothing in that situation — which is usually wrong.
Question 2
Are the cases mutually exclusive?
Can more than one case apply at the same time? If not, use elif. If they can overlap, use separate if statements.
Question 3
Is there always a default case?
If some input might not match any of your conditions, do you need an else to handle it? It acts as your safety net.
Question 4
Are conditions in the right order?
In an elif chain, Python stops at the first true condition. Make sure the most important or most specific cases come first.
Worked Example 6.8.1
Designing a ticket price calculator
  • RulesChildren under 12: $6.00. Students (12–17): $9.00. Adults (18–64): $13.00. Seniors (65+): $8.00.
  • List casesAge under 12 → child. Age 12–17 → student. Age 18–64 → adult. Age 65+ → senior. The cases are mutually exclusive and together cover every possible age, so an elif chain is appropriate.
age = 14 if age < 12: price = 6.00 elif age <= 17: price = 9.00 elif age <= 64: price = 13.00 else: price = 8.00 print(f"Ticket price: ${price:.2f}")

With age = 14: 14 < 12 → False. 14 <= 17 → True. Set price = 9.00. Stop.

Ticket price: $9.00
Why The Conditions Don't Spell Out Full Ranges

Notice that the conditions do not need to spell out the full range explicitly. Once age < 12 is false, you know age is at least 12. So age <= 17 catches ages 12 through 17 without needing to write 12 <= age <= 17. This relies on the order of evaluation — each elif implicitly knows that all previous conditions were false.

Worked Example 6.8.2
A membership eligibility check
  • RulesMembers under 18 must have a parent on the membership. Members must have paid their annual fee. Members with overdue fees get a notice, not access.
age = 15 parent_member = True fee_paid = True if not fee_paid: print("Your fee is overdue. Please pay to access the club.") elif age < 18 and not parent_member: print("Under-18 members require a parent membership.") else: print("Welcome to the club.")

Trace with the given values: not fee_paid → not True → False. Move to elif. age < 18 and not parent_member → 15 < 18 and not True → True and False → False. Move to else. The else block runs.

Welcome to the club.

This design checks the disqualifying conditions first (unpaid fee, missing parent membership) and only reaches "welcome" if everything passes. This pattern — check problems first, success last — is a useful habit for eligibility and validation logic.

Tracing Conditional Programs

Tracing is the process of following code exactly as Python executes it. Tracing conditional programs requires special attention because not all lines run every time. Which lines run depends entirely on the values of the variables and the conditions at each step.

A Disciplined Method for Tracing

1. Know the value of every relevant variable before each condition is evaluated.
2. Evaluate each condition to True or False.
3. Follow the correct branch.
4. Skip the branches that do not run.
5. Continue from the line after the full conditional structure.

Tracing Example 1
A simple elif chain
x = 7 if x > 10: print("Large") elif x > 5: print("Medium") else: print("Small") print("Done")
  • Step 1Evaluate x > 10 → 7 > 10 → False. Skip this block.
  • Step 2Evaluate x > 5 → 7 > 5 → True. Run this block.
  • Step 3print("Medium") executes.
  • Step 4Skip the else block.
  • Step 5print("Done") executes.
Medium Done
Tracing Example 2
A nested decision
username = "admin" password = "1234" if username == "admin": if password == "secret": print("Administrator access granted.") else: print("Correct username, wrong password.") else: print("Unknown user.")
  • Step 1Evaluate username == "admin" → True. Enter outer block.
  • Step 2Evaluate password == "secret" → "1234" == "secret" → False. Skip inner if.
  • Step 3Run inner else block.
Correct username, wrong password.
Tracing Example 3 — Predict the Output
Study this program and predict the output before reading on
a = 5 b = 10 if a > b: print("A is larger") b = a elif a == b: print("They are equal") else: print("B is larger") a = b print(f"a = {a}, b = {b}")
  • Condition 1a > b → 5 > 10 → False. Skip.
  • Condition 2a == b → 5 == 10 → False. Skip.
  • Else blockRuns. Prints "B is larger". Sets a = b, so a = 10.
  • Final printBoth variables are now 10.
B is larger a = 10, b = 10
A Reminder

Notice that the else block changes a. After the conditional structure, a has a new value. Conditional branches can modify variables, and those changes persist after the branch ends.

Using a Tracing Table

For complex programs, a tracing table helps you track variable values across steps. Here is a tracing table for the example above:

LineActionab
Start—510
if a > bFalse, skip510
elif a == bFalse, skip510
else: a = ba gets value of b1010
print(...)Output: a = 10, b = 101010

Tracing tables are especially useful when programs grow larger. You will practice them extensively in this chapter's exercises and in Chapter 10.

Avoiding Conditional Logic Errors

Conditional programs are prone to a specific set of mistakes. Knowing them in advance helps you spot them before they cause problems.

Error 1
Missing elif, using separate if statements instead
score = 95 if score >= 90: grade = "A" if score >= 80: grade = "B" if score >= 70: grade = "C"
With score = 95, all three conditions are true. grade ends up as "C" because the last assignment wins. The student with a 95 is labeled C. The fix is to use elif so the chain stops at the first match.
Error 2
Conditions that never match because of fragile equality checks
score = 75 if score == 100: print("Perfect") elif score == 90: print("Great") elif score == 75: print("Good") # This line runs else: print("Keep practicing")
This works, but exact equality (==) is fragile for scores. What if the score is 74 or 76? Neither matches any condition, so the else runs and prints "Keep practicing" for a student with 74. More commonly you want ranges, not exact values.
Error 3
Overlapping conditions in the wrong order create dead code
score = 55 if score >= 50: print("Passed") elif score >= 90: print("Excellent") # Never reached
Since score >= 50 is true for a score of 55, the chain stops immediately. The elif score >= 90 branch is dead code — it can never run for any score, because any score that is at least 90 is also at least 50, and the first condition will catch it first. Put more specific (or higher-threshold) conditions before more general ones.
Error 4
Using assignment = instead of equality == in a condition
# This is a bug x = 5 if x = 10: # SyntaxError in Python 3 print("Ten")
Python 3 will raise a SyntaxError here, which actually protects you. But the intent was x == 10. Remember: = is assignment, == is comparison.
Error 5
Forgetting the colon
if score >= 60 print("Passed")
Python raises a SyntaxError. The colon is required at the end of every if, elif, and else line.
Error 6
Incorrect indentation
score = 75 if score >= 60: print("Passed") # IndentationError: expected an indented block
The body of an if block must be indented, or Python raises an IndentationError. All lines in the same block must also use the same indentation, or Python raises an IndentationError: unexpected indent.
Error 7
Logic that is technically correct but misses edge cases
# Intended to catch scores below 0 and above 100 as invalid score = -5 if score >= 0 and score <= 100: print("Valid score") else: print("Invalid score")
This works. But what about score = 100.5? Or score = "eighty"? Conditionals only catch what you design them to catch. Think about your edge cases.
Error 8
Relying on a missing else when conditions do not cover all cases
color = "purple" if color == "red": print("Stop") elif color == "yellow": print("Slow down") elif color == "green": print("Go") else: print("Unknown signal")
The else here correctly handles any color that is not red, yellow, or green. But if the else had been left out and the input was "purple", the program would silently do nothing. Always consider whether your chain needs a default case.

Chapter Summary

Key Terms

conditional execution
Running a block of code only when a specified condition is true.
if statement
A Python construct that evaluates a condition and runs an indented block only if the condition is True.
code block
A group of consecutive indented lines in Python that belong to the same structure, such as an if statement or loop.
indentation
The whitespace at the start of a line that Python uses to define which lines belong to a block. The standard is four spaces per level.
else clause
An optional part of an if statement that provides a block of code to run when the if condition is False.
elif clause
Short for "else if." Adds additional conditions to test in sequence after an if. Only the first true branch runs.
mutually exclusive
Describes a set of conditions or cases where at most one can be true at a time. elif chains produce mutually exclusive branches.
nested decision
An if statement written inside the block of another if statement, creating multiple levels of conditional logic.
dead code
Code that can never execute because no combination of inputs can reach it. A common cause is an elif condition that is always caught by an earlier condition.
tracing table
A table used to record the values of variables and the results of conditions at each step of program execution.
default case
An else block that handles any input not matched by the preceding if or elif conditions.
edge case
An input value at the boundary of what a program is designed to handle — for example, the minimum, maximum, or an unusual special value.
PracticeCode Reading

Read each program carefully. Do not run it. Answer the questions below each program.

Code Reading 6.1

points = 47 if points >= 50: result = "Pass" else: result = "Fail" print(result)
  1. What does result equal after the conditional runs?
  2. What is printed?
  3. What would result be if points = 50?
  4. What would result be if points = 49?

Code Reading 6.2

hour = 14 if hour < 12: greeting = "Good morning" elif hour < 17: greeting = "Good afternoon" elif hour < 21: greeting = "Good evening" else: greeting = "Good night" print(greeting)
  1. What is greeting when hour = 14?
  2. What is greeting when hour = 9?
  3. What is greeting when hour = 23?
  4. What is greeting when hour = 17?

Code Reading 6.3

x = 8 y = 3 if x > 5: print("x is big") if y > 5: print("y is big") if x + y > 10: print("sum is big")
  1. How many print() calls execute?
  2. What is the output?
  3. Why were separate if statements used here instead of elif?
  4. What would the output be if y = 8?

Code Reading 6.4

membership = "gold" years = 3 if membership == "gold": if years >= 5: discount = 20 else: discount = 10 elif membership == "silver": discount = 5 else: discount = 0 print(f"Your discount is {discount}%.")
  1. What is discount with membership = "gold" and years = 3?
  2. What is discount with membership = "gold" and years = 7?
  3. What is discount with membership = "silver" and years = 10?
  4. What is discount with membership = "bronze" and years = 2?
PracticeCode Tracing

For each program, trace the execution step by step and fill in the tracing table. Predict the output before checking.

Tracing 6.1

temperature = 28 if temperature >= 35: status = "Extreme heat" elif temperature >= 28: status = "Hot" elif temperature >= 20: status = "Warm" else: status = "Cool" print(status)
StepCondition EvaluatedResultAction
1temperature >= 35  
2temperature >= 28  
Output   

Tracing 6.2

n = 12 if n % 2 == 0: print("Even") else: print("Odd") if n > 10: print("Greater than ten") print("Finished")

Complete the tracing table and write the full output.

LineConditionResultOutput
if n % 2 == 0   
if n > 10   
print("Finished")—— 

Tracing 6.3

Trace this nested conditional with a = 3 and b = 7.

a = 3 b = 7 if a < b: if a > 0: print("a is a positive number smaller than b") else: print("a is not positive but still smaller than b") else: print("a is not smaller than b")

Write out:

  1. The result of the outer condition.
  2. Whether Python enters the outer block.
  3. The result of the inner condition (if reached).
  4. Which print() runs.
  5. The full output.
PracticePredict the Output

Study each program and predict the exact output. Write your answer before checking.

Predict 6.1

score = 72 if score >= 90: print("A") elif score >= 80: print("B") elif score >= 70: print("C") elif score >= 60: print("D") else: print("F")

Predict 6.2

x = 10 if x > 5: print("Above five") if x > 8: print("Above eight") if x > 12: print("Above twelve")

Predict 6.3

value = 0 if value: print("Truthy") else: print("Falsy")

(Hint: recall from Chapter 5 that 0 is falsy in Python.)

Predict 6.4

a = 5 b = 5 if a > b: print("a wins") elif b > a: print("b wins") else: print("tie") a = a + 1 if a > b: print("a now wins")
PracticeDebugging Practice

Each program contains one or more errors. Identify each error, explain what is wrong, and write the corrected code.

Debug 6.1

age = 20 if age >= 18 print("Adult") else: print("Minor")

What is wrong? Write the corrected code.

Debug 6.2

score = 85 if score >= 90: print("A") if score >= 80: print("B") if score >= 70: print("C")

This program has a logic error for a student with a score of 85. What is wrong? Write the corrected code.

Debug 6.3

temperature = 15 if temperature > 30: print("Hot") elif temperature > 20: print("Warm") elif temperature > 10: print("Cool") else: print("Cold")

What is wrong? Write the corrected code.

Debug 6.4

username = "alice" if username = "alice": print("Welcome, Alice.") else: print("Unknown user.")

What is wrong? Write the corrected code.

Debug 6.5

speed = 85 if speed >= 120: print("Dangerously fast") elif speed >= 100: print("Over the limit") elif speed >= 80: print("Slightly over") elif speed >= 120: # Is this reachable? print("Also very fast") else: print("Within the limit")

Identify the dead code in this program and explain why it can never run.

PracticeShort Programming Tasks

Task 6.1 — Positive, Negative, or Zero

Write a program that asks the user for a number and prints whether it is positive, negative, or zero. Example output when input is -3:

The number is negative.

Task 6.2 — Driving Eligibility

Write a program that asks the user for their age and prints: "You may drive with a learner's permit." for ages 16 and 17; "You may drive with a full licence." for ages 18 and over; "You are not yet eligible to drive." for ages under 16.

Task 6.3 — Discount Calculator

A store offers these discounts on a purchase total:

Purchase TotalDiscount
Under $20No discount
$20 to $49.995%
$50 to $99.9910%
$100 or more15%

Write a program that reads a purchase total and prints the discount percentage and the final price after the discount.

Task 6.4 — Season Finder

Write a program that reads a month number (1 through 12) and prints the season: December, January, February → Winter; March, April, May → Spring; June, July, August → Summer; September, October, November → Autumn. Handle any month number outside 1–12 with an appropriate message.

Task 6.5 — Triangle Type

Write a program that reads three side lengths and prints: "Equilateral" if all three sides are equal; "Isosceles" if exactly two sides are equal; "Scalene" if all three sides are different; "Invalid" if any side is zero or negative. Check for "Invalid" first, before the other cases.

Task 6.6 — Simple Login System

Write a program that stores a correct username and password (as variables). Ask the user to enter a username and a password. Print "Access granted." if both match; "Wrong password." if the username matches but the password does not; "Unknown username." if the username does not match.

Mini-ProjectGrade and Scholarship Calculator

Design and write a program that takes a student's numeric score (0 to 100) and determines: their letter grade (A, B, C, D, or F) using standard thresholds; whether they qualify for an academic scholarship (score 90 or above); whether they are on academic probation (score below 60); and a short message appropriate to their result.

Requirements

Planning Step

Before writing any code, write out in plain language: What are the valid and invalid inputs? What are the possible grade cases? What are the possible message cases? Are any decisions nested?

Sample Output 1 (score = 94)
Student: Maria Chen Grade: A Congratulations! You qualify for an academic scholarship.
Sample Output 2 (score = 73)
Student: David Park Grade: C Good standing. Keep up your work.
Sample Output 3 (score = 54)
Student: Lena Schulz Grade: F You are on academic probation. Please speak with your adviser.
Sample Output 4 (score = 110)
Error: Score must be between 0 and 100.
Extension (Optional)

Add a second score (e.g., a midterm and a final). Compute the average and base the grade and messages on the average.

Mixed ReviewDrawing on Chapter 5 and Earlier Chapters

Review 6.1

Write the Boolean value (True or False) that each expression produces:

  1. 10 > 5 and 3 < 2
  2. 10 > 5 or 3 < 2
  3. not (5 == 5)
  4. "hello" == "Hello"
  5. 7 != 7

Review 6.2

A program stores x = 4. Write an if/else statement that prints "Even" if x is even and "Odd" if x is odd. Use the modulo operator %.

Review 6.3

Explain in plain language what this program does. Then predict the output for n = 15.

n = 15 if n % 3 == 0 and n % 5 == 0: print("FizzBuzz") elif n % 3 == 0: print("Fizz") elif n % 5 == 0: print("Buzz") else: print(n)

Review 6.4

A student writes this program to check whether a number is in a range:

value = 50 if value > 0: if value < 100: print("In range")

Rewrite this using a single compound condition and a single if statement. What is the output for value = 50? For value = 150?

Review 6.5

What is the difference between if/elif/else and a series of separate if statements? Describe a situation where you would use each.

Chapter 6 Checklist
Use this to confirm your understanding before moving to Chapter 7
Concepts
  • I can explain what conditional execution is and why programs need it.
  • I can write a correct if statement with a condition, colon, and indented block.
  • I can explain how Python uses indentation to define code blocks.
  • I can write an if/else statement and explain why exactly one branch runs.
  • I can write an elif chain to handle more than two mutually exclusive cases.
  • I can explain why the order of conditions in an elif chain matters.
  • I can distinguish between elif chains and separate if statements, and choose correctly.
  • I can write and trace a nested decision.
Applications
  • I can design branching logic by listing all cases before writing code.
  • I can decide whether a default else case is needed.
  • I can trace a conditional program by hand and predict its output.
  • I can build and use a tracing table for a multi-branch program.
Debugging Habits
  • I can identify dead code caused by conditions in the wrong order.
  • I can find and fix missing colons and indentation errors.
  • I know the difference between = and == and why mixing them up causes errors.
  • I check my conditional logic against edge cases before considering it finished.
Preview — Chapter 7
Loops and Repetition

Chapter 6 taught programs to make decisions. Now programs can take different paths. But programs also need to repeat work. Printing a hundred grades one by one is not practical. Counting votes manually is not practical. Processing thousands of entries one at a time in code would require thousands of lines. Repetition is one of the most powerful tools a program has. Chapter 7 introduces loops — the mechanism Python uses to repeat code. You will learn what a loop body is, how iteration works, how counters and accumulators keep track of repeated work, and the difference between repeating a fixed number of times versus repeating until a condition is met. Loops will also use conditions — the same Boolean logic and comparisons from Chapter 5. The skills from Chapters 5 and 6 feed directly into Chapter 7. Bring your understanding of True and False with you.

MGU Library Connection
  • Programming with Python — Appendix C: Python Syntax Quick Reference
  • Programming with Python — Appendix D: Common Python Error Messages
  • Programming with Python — Appendix E: Debugging Checklist
  • Companion resource: Conditionals Flowchart
  • Companion resource: Variable Tracing Worksheet
  • Next chapter: Loops and Repetition (Chapter 7)