MGU Computer Science Series — Computer Science Foundations
Part II: Programming Foundations
Conditionals · Loops · Control Flow · Tracing · Patterns
Chapter 8 of 28
MGU Computer Science Series  ·  Computer Science Foundations  ·  Library Textbook Edition

Chapter 8:
Conditionals, Loops,
and Control Flow

Boolean expressions, if statements, else and elif, nested decisions, while loops, for loops, counters, accumulators, and the skill of tracing programs step by step

■ Part II: Programming Foundations ■

■ 10 Sections  •  Chapter 8 of 28 ■

Follows Chapter 7: Variables, Types, and Expressions  ·  Prepares students for Chapter 9: Functions, Decomposition, and Reuse

Purpose and Overview

Every program you have seen so far runs in a straight line: step one, step two, step three, done. That is useful for short procedures, but almost no real program works that way. Real programs make decisions. They do different things depending on what they find. They repeat actions many times without you writing the same line over and over again. They skip steps, branch into alternatives, and keep running until a condition is satisfied.

This chapter introduces the tools that give programs this power. Those tools are called control flow structures. The two most important are conditionals — which let programs choose between paths — and loops — which let programs repeat actions automatically. Understanding these structures is one of the most important transitions in learning to program.

The chapter also introduces program tracing: following a program step by step on paper to predict what it will do. Tracing is one of the most important skills a programmer can develop. It teaches you to think like the computer executing the code, not just the programmer who wrote it.

Opening Scenario

A login system needs to check whether a password matches. If it does, let the user in. If it does not, show an error. A game character should keep moving until it hits a wall. A program should add up every number in a list of 10,000 entries without you writing 10,000 addition steps. All three of these require non-linear control flow — the ability for a program to take different paths, or repeat itself, based on what it discovers while running. By the end of this chapter, you will have the tools to write all of them.

10Sections
11Objectives
30+Key Terms
12+Worked Examples

Learning Objectives

  1. 1Define control flow and explain why it is needed in real programs.
  2. 2Write and evaluate Boolean expressions using comparison and logical operators.
  3. 3Distinguish the == comparison operator from the = assignment operator.
  4. 4Write if, if-else, and if-elif-else structures and explain what each one does.
  5. 5Read and trace nested conditionals step by step.
  6. 6Write a while loop that correctly terminates and explain what causes infinite loops.
  7. 7Write a for loop using range() and explain how it differs from a while loop.
  8. 8Implement counter and accumulator patterns inside loops.
  9. 9Identify and fix off-by-one errors and infinite loop bugs.
  10. 10Trace any program with conditionals and loops in a step-by-step table.
  11. 11Explain the modulo operator and use it to check for evenness or periodicity.

Sections at a Glance

Sections 8.1 – 8.2
Control Flow and Boolean Expressions
What Control Flow Means · Comparisons · Logical Operators · Expressions with Variables

What Control Flow Means

When a computer runs a program, it executes instructions one at a time. The flow of control is the path the computer takes through those instructions. In the simplest programs, control flows from the first line to the last in a straight, uninterrupted path.

But most real programs cannot follow a straight path. A login system needs to check whether a password is correct. An app needs to display different content depending on a user's settings. A program that sums a list of 10,000 numbers cannot have 10,000 addition lines written by hand. All of these require non-linear control flow — the program's path depends on something it discovers while running.

StructureWhat it doesExample use
ConditionalChooses between paths based on a conditionIf the score is above 60, print "Pass"
LoopRepeats a block of instructions multiple timesAdd each number in a list to a total
Function callJumps to a named block and returns (Chapter 9)Call a function to compute a square root
The Tracing Habit

The most important skill in this chapter is learning to trace — to follow a program's execution step by step, on paper, predicting what each line does and what value each variable holds. A program is not a description. It is a precise set of instructions that execute in a specific order. Tracing teaches you to read programs the way the computer runs them, not the way the programmer intended them.

Boolean Expressions and Comparisons

Before a program can choose between paths, it needs a way to ask a yes-or-no question. Those answers come from Boolean expressions. A Boolean expression is any expression that evaluates to exactly one of two values: True or False. There is no middle ground, no "maybe," and no "partially true."

Comparison Operators

OperatorMeaningExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
<Less than3 < 7True
>Greater than10 > 15False
<=Less than or equal to4 <= 4True
>=Greater than or equal to2 >= 9False
Critical Distinction — = vs. ==

In Python, a single = is the assignment operator — it sets a variable's value. A double == is the comparison operator — it asks whether two values are equal and returns True or False. Writing if x = 5: is a syntax error. Writing if x == 5: is a comparison. Mixing these up is the single most common beginner mistake in Python.

Comparison — Assignment vs. Equality
x = 10        # Assignment: x now holds the value 10
x == 10       # Comparison: asks "is x equal to 10?" → True
x == 5        # Comparison: asks "is x equal to 5?"  → False

Logical Operators

OperatorMeaningExampleResult
andBoth must be True(3 < 5) and (7 > 4)True
orAt least one must be True(3 < 1) or (7 > 4)True
notReverses True and Falsenot (5 == 5)False

You can think of these operators as mirrors of everyday language. "The score is above 60 and the student attended class" requires both conditions to hold. "The temperature is below 32 or it is raining" is satisfied by either condition. "The account is not locked" reverses the condition entirely. Boolean expressions become most powerful when they involve variables, because the result changes depending on the variable's value at any given moment.

Boolean Expressions with Variables
temperature = 28

temperature > 30      # False — 28 is not greater than 30
temperature >= 20     # True  — 28 is at least 20
temperature == 28     # True  — 28 equals 28
Practice 8.2Evaluating Boolean Expressions

Evaluate each expression as True or False. Assume x = 12, y = 5, z = 12.

  1. x == 12
  2. y > x
  3. x == z
  4. x != z
  5. y <= 5
  6. x > 10 and y < 10
  7. y > 10 or z == 12
  8. not (x == z)
Sections 8.3 – 8.5
Conditionals: Making Decisions in Code
If Statements · Else and Elif · Nested Decisions · Tracing

If Statements

An if statement tells the program: evaluate this condition. If it is True, execute this block of code. If it is False, skip it entirely. It is the simplest form of decision in programming, and it is the foundation for all the more complex conditional structures that follow.

If Statement — Structure

if condition:

instructions to run if condition is True

The colon after the condition is required. The indented lines form the block that runs when the condition is True. Lines at the same indentation level belong to the same block. Python uses indentation — not brackets or keywords — to group lines together.

A Simple If Statement
score = 85

if score >= 60:
    print("You passed.")
Trace 8.3.1
Tracing a simple if statement — two values
  • score = 8585 >= 60 is True. The indented block runs. Output: "You passed."
  • score = 4242 >= 60 is False. The indented block is skipped entirely. Nothing is printed.
Key insight: the same code produces different behavior based on the variable's value. This is control flow.
Indentation Is Not Decoration

In Python, indentation is part of the language's grammar. If the line inside an if block is not indented, Python raises an IndentationError. If it is indented but the if line is missing its colon, Python raises a SyntaxError. Both errors stop the program before it runs. Standard Python indentation is 4 spaces per level. Never mix tabs and spaces.

Else and Multiple Branches

An if statement handles the case when a condition is True. But what should happen when it is False? The else clause provides a second path. An if-else structure always runs exactly one of the two blocks: if the condition is True, the if block runs; if it is False, the else block runs. There is no situation where both run, and no situation where neither runs.

If-Else
score = 42

if score >= 60:
    print("You passed.")
else:
    print("You did not pass.")

Many decisions have more than two possibilities. For this, Python provides elif (short for "else if"), which adds additional conditions to check when all preceding conditions were False. Python evaluates the chain from top to bottom and runs only the first branch whose condition is True. Once a branch runs, the rest are skipped.

If-Elif-Else — Grade Classification
grade = 73

if grade >= 90:
    letter = "A"
elif grade >= 80:
    letter = "B"
elif grade >= 70:
    letter = "C"
elif grade >= 60:
    letter = "D"
else:
    letter = "F"

print("Your grade is:", letter)
Trace 8.4.1
Tracing the elif chain — grade = 73
  • Step 1Evaluate 73 >= 90: False. Skip this block.
  • Step 2Evaluate 73 >= 80: False. Skip this block.
  • Step 3Evaluate 73 >= 70: True. Run this block: letter = "C". Stop checking.
  • Step 4The elif grade >= 60 and else branches are never evaluated.
  • OutputYour grade is: C
Only one branch runs. Once a True condition is found, the rest of the chain is skipped.
Practice 8.4Predict the Output

For each value of the variable, trace the code and write the exact output.

score = 78       # change this value for each question

if score >= 90:
    print("Distinction")
elif score >= 60:
    print("Pass")
else:
    print("Fail")
  1. score = 78
  2. score = 95
  3. score = 40
  4. score = 60
  5. score = 90
  6. score = 59

Nested Decisions

Sometimes a decision depends on more than one condition checked in sequence — not combined with and, but evaluated one inside the other. This is called nesting: placing one if statement inside another. The inner if only runs when the outer condition is True. This is useful when the second question only makes sense if the first question answered a certain way.

Nested Conditionals — Event Entry
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("You must be 18 or older.")
Trace 8.5.1
Nested conditionals — three cases
  • age=20, ticket=True20 >= 18 True → enter outer if. has_ticket True → inner if runs. Output: "Welcome. Enjoy the event."
  • age=20, ticket=False20 >= 18 True → enter outer if. has_ticket False → inner else runs. Output: "You need a ticket to enter."
  • age=15, ticket=True15 >= 18 False → outer else runs. Output: "You must be 18 or older." The inner if is never reached.
When outer condition is False, the entire inner structure is skipped. The inner if only becomes reachable once the outer condition passes.
Nested vs. Combined Conditions

When both conditions need to be True and there are no separate alternatives for each, combining with and is often cleaner: if age >= 18 and has_ticket:. Nesting is preferable when the inner condition has its own else branch that only makes sense in context of the outer condition passing. Avoid nesting more than two or three levels deep — deep nesting is difficult to read and often signals that the logic should be restructured.

Practice 8.5Nested Conditionals
  1. Trace the event entry code for: (a) age=17, ticket=True; (b) age=20, ticket=False; (c) age=25, ticket=True. Write the output for each.
  2. Rewrite the event entry code using a combined and condition. When does the combined version behave differently from the nested version? When does it behave the same?
  3. Write nested conditionals for this scenario: A bank account allows withdrawal only if the account is active AND the balance is above zero. If inactive, print "Account closed." If active but zero balance, print "Insufficient funds." If active with funds, print "Withdrawal approved."
Sections 8.6 – 8.8
Loops: Repeating Instructions Automatically
Why Loops Exist · While Loops · For Loops · Range · Tracing

Repetition and Loops

Suppose you need to print the numbers from 1 to 10. One approach is to write ten separate print statements. That works for ten numbers, but it is completely impractical for a thousand, let alone a million. More importantly, it requires you to know the count in advance, write each case by hand, and change every line if the task changes.

Loops solve this problem by describing the pattern once and letting the computer repeat it. A loop is a control structure that repeats a block of instructions multiple times — either a fixed number of times, or until a condition changes. Every loop has two essential components: a loop body (the block of instructions to repeat) and a stopping mechanism (something that eventually causes the loop to end). If a loop never stops, it runs forever. Understanding how loops stop is just as important as understanding how they run.

Loop typeBest used whenStopping mechanism
While loopYou repeat until a condition changes; count unknown in advanceCondition becomes False
For loopYou iterate through every item in a sequence; count is knownSequence is exhausted

While Loops

A while loop checks a condition before each iteration. If the condition is True, the loop body runs. Then the condition is checked again. This continues until the condition becomes False, at which point the loop ends and execution continues with the next instruction after the loop.

While Loop — Structure

while condition:

loop body

The loop body must include something that eventually makes the condition False. If nothing inside the loop changes the condition, the loop will run without stopping — an infinite loop.

Basic While Loop — Counting 1 to 5
count = 1

while count <= 5:
    print(count)
    count = count + 1

print("Done")
Iterationcount (before check)count <= 5Actioncount (after)
11Trueprint 12
22Trueprint 23
33Trueprint 34
44Trueprint 45
55Trueprint 56
66Falseloop ends—

Output: 1 2 3 4 5 Done (each number on its own line, then "Done").

Notice that count = count + 1 is inside the loop body. This is essential: if count never changed, the condition count <= 5 would always be True, and the loop would never stop. Every while loop must include something in the body that moves the program toward the stopping condition.

While Loops for Input Validation

While loops are especially useful when you need to keep asking for input until the user provides a valid response. You do not know in advance how many attempts will be needed — which is exactly when a while loop is more appropriate than a for loop.

Input Validation with While Loop
password = input("Enter password: ")

while password != "open_sesame":
    print("Incorrect. Try again.")
    password = input("Enter password: ")

print("Access granted.")
Practice 8.7While Loop Tracing
  1. Trace the counting loop from the section with count = 1, but change the condition to count <= 3. Complete a trace table. What is the output?
  2. A student writes: n = 10 / while n > 0: / print(n) / n = n - 3. Complete a trace table. What are all values printed? What is the final value of n when the loop ends?
  3. How many times does this loop run? Trace it: x = 32 / while x > 1: / x = x // 2. (// is integer division: 7 // 2 = 3.)

For Loops

A for loop repeats a block of code once for each item in a sequence. Unlike a while loop, the for loop automatically moves through each item in order. You do not need to manually track a counter variable or write a condition that eventually becomes False. The loop ends naturally when all items have been processed.

For Loop — Structure

for item in sequence:

loop body using item

Each iteration, item takes on the value of the next element in the sequence. When the sequence is exhausted, the loop ends automatically.

Iterating Over a Range

The range() function generates a sequence of integers. range(5) produces 0, 1, 2, 3, 4. range(1, 6) produces 1, 2, 3, 4, 5. The stop value is always excluded — the sequence goes up to, but does not include, the stop number.

For Loop with range()
for i in range(1, 6):
    print(i)
IterationiAction
11print 1
22print 2
33print 3
44print 4
55print 5
——sequence exhausted, loop ends

Iterating Over a List

For Loop Over a List
fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

Output: apple, banana, cherry (each on its own line). Each iteration, fruit takes on the next value from the list.

For Loop vs. While Loop — When to Use Each

SituationBetter choice
You know exactly how many times to repeatfor loop with range()
You are processing every item in a list or sequencefor loop
You repeat until a condition changeswhile loop
You do not know in advance how many iterations you needwhile loop
You need input validationwhile loop
Practice 8.8For Loop Practice
  1. What does range(3) produce?
  2. What does range(2, 8) produce?
  3. What does range(0, 10, 2) produce?
  4. Write a for loop that prints every item in ["red","green","blue"].
  5. Write a for loop that prints 10, 9, 8 … 1 in that order. (Hint: range(10, 0, -1))
  6. Write a for loop that prints the multiplication table for 4, from 4×1 to 4×10.
Sections 8.9 – 8.10
Patterns, Errors, and Debugging
Counters · Accumulators · Modulo · Infinite Loops · Off-by-One · Tracing Strategies

Counters and Accumulators

Two patterns appear so frequently in loops that every programmer should recognize them immediately: counters and accumulators. Both involve a variable that is set to a starting value before the loop begins and updated systematically inside the loop body.

Counters

A counter is a variable that increases by a fixed amount each iteration, keeping track of how many times some condition has been met.

Counter Pattern — Count Even Numbers
count = 0

for i in range(1, 11):
    if i % 2 == 0:
        count = count + 1

print("Even numbers between 1 and 10:", count)
The Modulo Operator %

The % operator returns the remainder after integer division. 7 % 3 is 1 (7 ÷ 3 = 2 remainder 1). 10 % 2 is 0 (10 divides evenly by 2). i % 2 == 0 is True when i is even, because even numbers leave no remainder when divided by 2. Modulo is used constantly in programming: checking divisibility, wrapping values around a range, and detecting periodic events.

Accumulators

An accumulator is a variable that collects a running total as the loop processes each item. The most common form is a sum accumulator, but accumulators can also concatenate strings, build lists, or track any value that grows with each iteration.

Accumulator Pattern — Running Sum
total = 0
numbers = [12, 7, 25, 3, 41, 18]

for n in numbers:
    total = total + n

print("Sum:", total)
Iterationntotal (before)total (after)
112012
271219
3251944
434447
5414788
61888106
———Output: Sum: 106
Always Initialize Before the Loop

A counter or accumulator must be assigned a starting value before the loop begins. If total = 0 were placed inside the loop body instead of before it, total would be reset to 0 at the start of every iteration, destroying the running total. Initialization outside the loop is not optional — it is part of the pattern.

Combined Counter and Accumulator — Computing an Average
total = 0
count = 0
numbers = [15, 8, 22, 6, 30]

for n in numbers:
    total = total + n
    count = count + 1

average = total / count
print("Count:", count)
print("Total:", total)
print("Average:", average)

Output: Count: 5 / Total: 81 / Average: 16.2. This pattern — accumulating a sum and counting items to compute an average — appears constantly in data processing, science, finance, and everyday programs.

Practice 8.9Counter and Accumulator Practice
  1. Complete a trace table for the even-number counter, showing values of i, i % 2, the condition result, and count for each iteration from i=1 to i=6.
  2. Write a counter loop that counts how many numbers in [5, 14, 3, 22, 8, 11, 1] are greater than 10. Show expected output.
  3. Write an accumulator loop that finds the product (multiplication) of all numbers in [2, 3, 4, 5]. What must the accumulator be initialized to? Why?
  4. Write a program using both a counter and an accumulator to find the count and total of all negative numbers in [-3, 7, -1, 4, -9, 2, -5].

Infinite Loops and Loop Errors

An infinite loop is a loop that never ends because its stopping condition never becomes False. It is one of the most common and frustrating bugs in programming. The program appears to freeze or hang — it is actually running the same instructions over and over without ever moving forward. Understanding what causes infinite loops, and how to prevent them, is an essential part of writing correct code.

Error 8.10.1
Infinite loop — loop variable not updated
  • Broken
    count = 1
    while count <= 5:
        print(count)
        # count is never changed — loop runs forever
  • ProblemThe condition count <= 5 is always True because count never changes. The program prints 1 indefinitely.
  • FixAdd count = count + 1 inside the loop body. Now count increases each iteration and eventually becomes 6, making the condition False.
Rule: every while loop must include something in the body that moves the program toward the stopping condition.

Off-By-One Errors

An off-by-one error occurs when a loop runs one time too many or one time too few because the boundary condition is written incorrectly. It is called "off-by-one" because the error is usually exactly one iteration in the wrong direction.

Off-by-One Error — range()
# Intended to print 1 through 5
for i in range(1, 5):    # Produces 1, 2, 3, 4 — misses 5
    print(i)

# Correct version
for i in range(1, 6):    # Produces 1, 2, 3, 4, 5
    print(i)

range(1, 5) produces numbers from 1 up to but not including 5. The stop value is always excluded. This trips up many beginners: when you want to include the value 5 in your range, you must write range(1, 6). Similarly, in while loops, the difference between < and <= in the boundary condition determines whether the final value is included.

Debugging Loops

The most reliable method for debugging a loop is to trace it by hand. Take a small version of the data, trace the loop iteration by iteration in a table, and check whether the values change as expected. If the trace reveals unexpected behavior, the cause is usually one of: the wrong initial value, the wrong boundary condition (< vs. <=), or a missing or misplaced update to the loop variable.

You can also add print statements inside the loop temporarily to see what is happening at each step. These diagnostic prints reveal the state of your variables at every iteration. Remove them once the loop is working correctly.

Diagnostic Print Statements for Debugging
total = 0
for i in range(1, 6):
    print("i is:", i, "  total before:", total)
    total = total + i
    print("  total after:", total)
Practice 8.10Finding and Fixing Loop Errors

Each fragment contains an error. Identify the error type and write the corrected version.

Error A — Missing update
n = 10 / while n > 0: / print(n)

What happens when you run this? What is missing? Write the fix.

Error B — Off-by-one
for i in range(1, 10): print(i) — intended to print 1 through 10

What does this actually print? What should the range be?

Error C — Uninitialized accumulator
for n in [3, 7, 2]: total = total + n / print(total)

What error will Python raise? What must be added, and where?

Error D — Wrong operator
count = 0 / while count < 5: / print(count) / count = count + 1 — intended to print 0, 1, 2, 3, 4, 5

This prints 0–4, not 0–5. What single character change fixes it?

Chapter Summary

Key Terms Review

accumulator
A variable that collects a running total across loop iterations. Must be initialized to a starting value before the loop begins.
Boolean expression
An expression that evaluates to exactly True or False. Used as conditions in if statements and loops.
branch
One of the possible paths through a conditional structure. Only one branch executes per evaluation of the chain.
comparison operator
A symbol that compares two values and returns True or False: ==, !=, <, >, <=, >=.
condition
A Boolean expression used to control which path a program takes, or whether a loop continues running.
conditional
A control structure that chooses between paths based on a Boolean condition. Includes if, if-else, and if-elif-else.
control flow
The order in which a program's instructions execute. Changed by conditionals, loops, and function calls.
counter
A variable that increases by a fixed amount each loop iteration to count how many times a condition is met.
elif
"Else if." A clause that adds another condition to check when all preceding conditions were False. Runs at most once per chain evaluation.
else
A clause that runs when all preceding conditions in an if-elif-else chain are False.
for loop
A loop that iterates once for each item in a sequence, automatically moving to the next item each iteration.
if statement
A conditional structure that executes a block of code when its Boolean condition is True and skips the block when False.
indentation
Whitespace at the start of a line. Python uses indentation to define which lines belong to the same block. Required in if statements and loops.
infinite loop
A loop whose condition never becomes False, causing the program to run without stopping.
initialization
Assigning a starting value to a variable before it is used, especially before a counter or accumulator enters a loop.
iteration
One complete pass through a loop body.
logical operator
An operator that combines Boolean expressions: and, or, and not.
loop
A control structure that repeats a block of instructions multiple times.
loop body
The indented block of instructions that a loop repeats each iteration.
modulo operator
The % operator. Returns the remainder after integer division. 7 % 3 equals 1.
nesting
Placing one control structure inside another — for example, an if inside an if, or a loop inside a conditional.
off-by-one error
A loop error where the loop runs one iteration too many or too few due to an incorrect boundary condition.
range()
A Python function that generates a sequence of integers. The stop value is excluded. range(1, 6) produces 1, 2, 3, 4, 5.
tracing
Following a program's execution step by step in a table to predict its output and verify its behavior. An essential debugging skill.
while loop
A loop that repeats its body as long as a condition is True. Stops when the condition becomes False. The body must include something that eventually changes the condition.

Diagram Review

Control Flow Diagrams

If-Else Structure
         Start
           │
     [Evaluate Condition]
           │
      ┌────┴────┐
    True      False
      │          │
  [If Block]  [Else Block]
      │          │
      └────┬─────┘
           │
         Continue
While Loop Structure
         Start
           │
     [Evaluate Condition] ◄──────────┐
           │                         │
      ┌────┴────┐                    │
    True      False                  │
      │          │                   │
  [Loop Body]  [Exit Loop]           │
      │                              │
      └──────────────────────────────┘
For Loop Structure
         Start
           │
     [More items in sequence?] ◄─────┐
           │                         │
      ┌────┴────┐                    │
     Yes       No                    │
      │          │                   │
  [Set loop   [Exit Loop]            │
   variable                          │
   to next item]                     │
      │                              │
  [Loop Body]                        │
      │                              │
      └──────────────────────────────┘

Code Review

Exercise 8.ARead and Analyze
x = 14

if x > 10:
    print("large")
elif x > 5:
    print("medium")
else:
    print("small")
  1. What is the output when x = 14?
  2. What would the output be if x = 7?
  3. What would the output be if x = 3?
  4. Is it possible for both "large" and "medium" to print in the same run? Why or why not?
Exercise 8.BComplete the Trace Table
total = 0

for i in range(1, 6):
    total = total + i

print(total)
Iterationitotal (before adding)total (after adding)
1   
2   
3   
4   
5   

What is the final output?

Exercise 8.CFind the Bug
count = 0

while count < 5:
    print(count)

print("Done")
  1. What error does this code have?
  2. What would the computer do if you ran it?
  3. Write the corrected version.

Practice Questions

Part AVocabulary in Context
  1. A condition that evaluates to either True or False is called a ________ expression.
  2. The elif keyword stands for ________.
  3. A loop that runs without stopping because its condition never becomes False is called an ________ loop.
  4. A variable that increases by 1 each iteration to count occurrences is called a ________.
  5. Following a program's execution step by step on paper is called ________.
  6. The operator that returns the remainder after division is the ________ operator, written ________.
  7. In Python, lines that belong to the same block must share the same ________.
Part BPredicting Output

Trace each code fragment and write the exact output.

  1. x = 8
    if x > 10:
        print("A")
    elif x > 5:
        print("B")
    else:
        print("C")
  2. for i in range(3):
        print(i * 2)
  3. n = 1
    while n <= 16:
        n = n * 2
    print(n)
  4. total = 0
    for i in range(1, 5):
        if i % 2 == 0:
            total = total + i
    print(total)
  5. a = True
    b = False
    print(a and b)
    print(a or b)
    print(not a)
Part CDesign Questions
  1. Write a program that asks the user to enter a number between 1 and 10. If the number is in range, print "Valid." If it is not, print "Out of range." Use an if-else structure.
  2. Write a loop that prints the multiplication table for 7 (7×1 through 7×10) in this format: 7 x 1 = 7, 7 x 2 = 14, and so on through 7 x 10 = 70.
  3. Write a program that counts how many even numbers are in this list and what their sum is: [3, 16, 7, 22, 5, 14, 9, 8, 11, 20]. Use a single loop with a conditional inside it.
  4. Write a program using a while loop that keeps asking the user to enter a positive number and adds it to a running total. The loop should stop when the user enters 0. At the end, print the total.
  5. A teacher wants to find the highest score in a class. Write a program that uses a loop to go through scores = [78, 92, 65, 88, 71, 95, 83, 60, 77, 89] and tracks the highest score found so far. Print the highest score after the loop. (Hint: initialize highest = scores[0] before the loop.)

Error Analysis

Each problem contains an error. Identify the error type (syntax, logic, or runtime), explain what went wrong, and write the corrected version.

Problem 1
2(x + 3) + 4x = 2x + 3 + 4x = 6x + 3

A student writes 5(2x − 3) and gets 10x − 3. What is the error? What is correct?

Problem 2 — Wrong operator
if x = 5: / print("five")

Identify the error and classify it. Explain why it occurs and write the fix.

Problem 3 — Incomplete distribution
temperature = 20 / if temperature > 30 / print("Hot")

What is missing? What type of error is this? Write the correct version.

Problem 4 — Two errors
total = 0 / count = 0 / for n in [4,7,2,9]: / total = total + n / count + 1 / average = total / count

There are two errors. Find both. What are their types? Write corrected code.

Problem 5 — Wrong classification
n = -5 / if n > 0: print("Positive") / if n == 0: print("Zero") / if n < 0: print("Negative")

The code works for this value of n. A classmate says it should use elif. Explain why elif is preferable and what problem could arise if the conditions were not mutually exclusive.

Real-World Applications

Application 8.1Login Systems

Nearly every application that requires an account uses a loop to handle failed login attempts. Describe in pseudocode or Python how a while loop and a conditional together could implement a login system that: allows up to three attempts; prints a success message if the password matches; prints a lockout message if all three attempts fail.

Application 8.2Streaming Recommendations

A streaming service wants to recommend content based on a user's stated mood: "action", "comedy", "drama", or "documentary". Each mood maps to a different recommendation. Write pseudocode or Python code that reads the user's mood and prints the recommendation. Include an else branch for unrecognized moods.

Application 8.3Inventory Analysis

A store tracks stock quantities. Write a program that processes stock = [0, 12, 3, 0, 7, 1, 0, 5, 9, 2] and counts: how many items are out of stock (quantity = 0); how many are low (1–5); how many are well-stocked (above 5). Print all three counts at the end.

Application 8.4Weather Analysis
temps = [22, 28, 31, 25, 29, 33, 30, 27, 24, 26,
         31, 28, 22, 20, 25, 29, 34, 32, 27, 23,
         21, 28, 30, 31, 26, 24, 29, 33, 28, 25]

Using this list of 30 daily temperatures, write a program that: counts how many days exceeded 30°C; finds the total of all temperatures; computes the monthly average. Print all three results.

Mixed Review

  1. (Chapters 4 and 8) Binary numbers can be compared like decimal numbers. Is 1010 in binary greater than, equal to, or less than 1001 in binary? Explain how a program might use a comparison operator to test this relationship once both values are stored as integers.
  2. (Chapters 7 and 8) A variable name holds a string. Write an if statement that checks whether name equals "admin" and prints "Access granted" if it does and "Access denied" if it does not.
  3. (Chapters 5 and 8) An algorithm is described informally as: "Keep asking the user for a number until they enter a number greater than 100." Translate this into a while loop in pseudocode. Identify the condition, the loop body, and the stopping mechanism.
  4. (Chapters 3 and 8) Explain how the computational thinking habit of decomposition relates to breaking a complex conditional problem into a series of simpler yes-or-no questions. Give a real-world example.
  5. (Chapter 6 and 8) Explain the difference between a syntax error and a logic error in the context of a for loop. Give one example of each.

Chapter 8 Checkpoint

Chapter 8 Checkpoint
Complete without assistance — assesses all key skills from Chapter 8
Section 1 — Vocabulary and Concepts
  1. What is a Boolean expression? What are the only two values it can produce?
  2. Explain the difference between = and == in Python with an example of each.
  3. In an if-elif-else chain, can more than one branch execute? Explain why or why not.
  4. What is an infinite loop? What is the most common cause?
  5. What does range(2, 9) produce? How many values does it generate?
Section 2 — Tracing
  1. Trace this code and write all output: x = 5 / if x > 3: print("big") / elif x > 1: print("medium") / else: print("small")
  2. Complete a full trace table for: total = 0 / for i in range(1, 5): / total = total + i / print(total)
  3. Trace this while loop and write all output: n = 10 / while n > 2: / print(n) / n = n // 2
Section 3 — Skills
  1. Write a for loop that prints all multiples of 3 from 3 to 30.
  2. Write a counter loop that counts how many numbers in [4, 15, 6, 22, 3, 18, 9] are greater than 10.
  3. Write an accumulator loop that sums all the numbers in [7, 3, 11, 5, 9, 2].
  4. Write an if-elif-else structure that classifies a temperature: below 0 → "Freezing", 0–14 → "Cold", 15–24 → "Mild", 25+ → "Hot".
Section 4 — Error Analysis
  1. A student writes while count < 10: / print(count). What is wrong? What type of error is this?
  2. A student writes for i in range(1, 10): intending to include 10 in the output. What should they write instead?
  3. A student writes if score = 100: print("Perfect"). Identify the error, classify it, and write the corrected line.
Looking Ahead
Chapter 9: Functions, Decomposition, and Reuse

Chapter 8 gave you the tools to make programs that decide and repeat. As programs grow larger, writing all the instructions in one block becomes unmanageable — the same logic gets repeated in multiple places, and the code becomes difficult to understand, test, and fix. Chapter 9 introduces functions: named, reusable blocks of code that solve a specific part of a problem. Functions let you write an instruction once, give it a name, and call it as many times as needed from anywhere in a program. You will learn to define functions, pass values into them using parameters, and receive results using return values. Functions are the foundation of decomposition in programming — breaking a large, complex problem into small, clearly named, independently tested parts. Every skill you built in Chapter 8 will be used inside functions in Chapter 9 and beyond.

MGU Library Connection
  • Python Syntax Quick Reference — Appendix D of this textbook
  • Pseudocode and Flowchart Reference — Appendix C of this textbook
  • Debugging and Testing Reference — Appendix E of this textbook
  • Chapter 5: Algorithms and Instructions — for pseudocode foundations
  • Chapter 9: Functions, Decomposition, and Reuse — next chapter
  • Python Programming Foundations — the dedicated programming course in the MGU CS series