In-Class Python Exercise 4

Python Code Explanation Exercises
Student task: Explain each program out loud as if you were in a technical interview. Begin with the program's overall purpose, then explain the code step by step, and finish by predicting the output.

Exercise 1 · Explain This Python Loop (Counting Even Numbers)

Python · Beginner
Explain this code out loud. Focus on the list, loop variable, modulo operator, counter, and final output.
numbers = [3, 8, 11, 14, 20]
even_count = 0

for number in numbers:
    if number % 2 == 0:
        even_count += 1

print(even_count)
🎯 Instructions oral task
  1. Explain the overall purpose of the program.
  2. Describe what is stored in the numbers list.
  3. Explain how the for loop processes the list.
  4. Explain what the modulo operator % does.
  5. Explain why the program compares the remainder to zero.
  6. Explain how even_count += 1 changes the counter.
  7. State the final value printed to the console.
📖 Vocabulary core
  • iteration — one cycle of a loop.
  • loop variable — a variable that represents the current item during a loop.
  • modulo operator — an operator that returns the remainder after division.
  • counter — a variable used to record how many times something happens.
  • even number — a number that can be divided by two without a remainder.
  • increment — to increase a value, usually by one.
🧩 Collocations natural English
  • iterate through a list
  • check each number
  • calculate the remainder
  • increment the counter
  • satisfy the condition
  • print the final result
🗣️ Phrasal Verbs interview speech
  • go through — “The loop goes through every number in the list.”
  • add up — “The program adds up the number of even values.”
  • keep track of — “The counter keeps track of how many even numbers are found.”
  • end up with — “The program ends up with a count of three.”
🎤 Model Answer spoken

This program counts how many even numbers appear in a list. The variable numbers stores five integers, and even_count starts at zero.

The for loop goes through the list one item at a time. During each iteration, the current value is stored in the variable number.

The condition uses the modulo operator to divide the number by two and check the remainder. If the remainder is zero, the number is even. The statement even_count += 1 then increments the counter by one.

The even numbers are 8, 14, and 20, so the final output is 3.

Exercise 2 · Explain This Python Function (Filtering Prices)

Python · Beginner+
Explain this function out loud. Focus on parameters, list creation, filtering logic, the append() method, and the returned list.
def get_expensive_items(prices, minimum_price):
    expensive_items = []

    for price in prices:
        if price >= minimum_price:
            expensive_items.append(price)

    return expensive_items

result = get_expensive_items([12, 45, 8, 60, 30], 30)
print(result)
🎯 Instructions oral task
  1. Explain what the function is designed to do.
  2. Describe the purpose of both parameters.
  3. Explain why an empty list is created.
  4. Explain how the function filters the prices.
  5. Describe what append() does.
  6. Explain the difference between return and print.
  7. Predict the final list displayed in the console.
📖 Vocabulary core
  • parameter — a named input defined by a function.
  • argument — an actual value passed into a function.
  • filter — to select values that meet a condition.
  • empty list — a list that initially contains no items.
  • list method — a built-in operation that can be performed on a list.
  • return value — the result sent back by a function.
🧩 Collocations natural English
  • pass in an argument
  • create an empty list
  • filter the data
  • append an item
  • meet the minimum price
  • return the filtered results
🗣️ Phrasal Verbs interview speech
  • pass in — “We pass in a list of prices and a minimum value.”
  • leave out — “The function leaves out prices below thirty.”
  • build up — “The function builds up a new list during the loop.”
  • send back — “The return statement sends back the filtered list.”
🎤 Model Answer spoken

This function filters a list of prices and returns only the values that are greater than or equal to a specified minimum.

The prices parameter represents the original list, while minimum_price represents the threshold. The function creates an empty list called expensive_items to store matching values.

The loop checks every price. When a price meets the condition, the append() method adds it to the new list. After the loop finishes, the function returns the completed list.

The values 45, 60, and 30 meet the minimum price, so the console displays [45, 60, 30].

Exercise 3 · Explain This Dictionary Function (Student Grade Report)

Python · Pre-Intermediate
Explain this code out loud. Focus on dictionary access, key-value pairs, calculation, formatted strings, and the returned message.
def create_grade_report(student):
    average = sum(student["scores"]) / len(student["scores"])

    if average >= 70:
        status = "Pass"
    else:
        status = "Fail"

    return f'{student["name"]}: {average:.1f} - {status}'

student_data = {
    "name": "Mika",
    "scores": [78, 65, 82]
}

print(create_grade_report(student_data))
🎯 Instructions oral task
  1. Explain how the student data is structured.
  2. Define a dictionary key and a dictionary value.
  3. Explain how the program accesses the student's scores.
  4. Explain how the average is calculated.
  5. Describe how the pass-or-fail decision is made.
  6. Explain the purpose of the formatted string.
  7. Explain what :.1f does.
  8. State the final output.
📖 Vocabulary core
  • dictionary — a data structure that stores information as key-value pairs.
  • key-value pair — a label and the value associated with that label.
  • data structure — a way of organizing and storing data.
  • average — the total of several values divided by the number of values.
  • formatted string — a string that includes inserted variables or expressions.
  • decimal precision — the number of digits displayed after the decimal point.
🧩 Collocations natural English
  • access a dictionary value
  • retrieve the scores
  • calculate an average
  • assign a status
  • format the output
  • display one decimal place
🗣️ Phrasal Verbs interview speech
  • look up — “The program looks up the values using dictionary keys.”
  • work out — “It works out the student's average score.”
  • round off — “The output rounds off the average to one decimal place.”
  • put together — “The f-string puts together the name, average, and status.”
🎤 Model Answer spoken

This program creates a short grade report from a dictionary. The dictionary stores the student's name and a list of scores as key-value pairs.

The function accesses the score list using the key "scores". It adds the scores with sum() and divides the total by the number of scores returned by len().

Next, an if statement checks whether the average is at least 70. If it is, the status is set to "Pass"; otherwise, it is set to "Fail".

The f-string combines the student's name, average, and status. The format specifier :.1f displays the average with one digit after the decimal point. The final output is Mika: 75.0 - Pass.

Exercise 4 · Explain This Error-Handling Function (Safe Division)

Python · Intermediate
Explain this function out loud. Focus on type conversion, exception handling, multiple exception types, and safe program behavior.
def safe_divide(value, divisor):
    try:
        number = float(value)
        result = number / divisor
        return round(result, 2)

    except ValueError:
        return "The value must be numeric."

    except ZeroDivisionError:
        return "The divisor cannot be zero."

print(safe_divide("25", 4))
print(safe_divide("hello", 4))
print(safe_divide("25", 0))
🎯 Instructions oral task
  1. Explain the purpose of the function.
  2. Explain why float() is used.
  3. Describe what happens inside the try block.
  4. Explain what an exception is.
  5. Explain when a ValueError occurs.
  6. Explain when a ZeroDivisionError occurs.
  7. Explain why error handling is useful.
  8. State all three outputs in the correct order.
📖 Vocabulary core
  • type conversion — changing a value from one data type to another.
  • exception — an error that occurs while a program is running.
  • exception handling — code that detects and responds to runtime errors.
  • try block — the section containing code that may cause an exception.
  • except block — the section that handles a specific exception.
  • runtime error — an error that happens while the program is executing.
🧩 Collocations natural English
  • convert a string to a float
  • raise an exception
  • catch an error
  • handle invalid input
  • prevent a crash
  • return an error message
🗣️ Phrasal Verbs interview speech
  • deal with — “The except blocks deal with two different errors.”
  • fall back on — “The program falls back on an error message when the calculation fails.”
  • break down — “Without exception handling, the program could break down.”
  • carry on — “Error handling allows the program to carry on safely.”
🎤 Model Answer spoken

This function safely divides a value by a divisor. It first attempts to convert the value into a floating-point number because the original input may be a string.

The conversion and division take place inside a try block. If both operations succeed, the result is rounded to two decimal places and returned.

A ValueError occurs when the string cannot be converted into a number. A ZeroDivisionError occurs when the divisor is zero. Each except block catches one error and returns a clear message instead of allowing the program to crash.

The three outputs are 6.25, The value must be numeric., and The divisor cannot be zero.

Exercise 5 · Explain This Class (Inventory Management)

Python · Intermediate+
Explain this code out loud. Focus on classes, objects, attributes, methods, object state, and method calls.
class Product:
    def __init__(self, name, quantity):
        self.name = name
        self.quantity = quantity

    def sell(self, amount):
        if amount <= self.quantity:
            self.quantity -= amount
            return f"Sold {amount} units."
        return "Not enough stock."

    def get_status(self):
        return f"{self.name}: {self.quantity} units available"

laptop = Product("Laptop", 5)

print(laptop.sell(2))
print(laptop.get_status())
print(laptop.sell(4))
🎯 Instructions oral task
  1. Explain what the Product class represents.
  2. Explain the purpose of the constructor.
  3. Describe the meaning of self.
  4. Identify the object's attributes.
  5. Explain how the sell() method updates the quantity.
  6. Explain why the second sale is rejected.
  7. Describe what the get_status() method returns.
  8. State all outputs in order.
📖 Vocabulary core
  • class — a blueprint used to create objects.
  • object — a specific instance created from a class.
  • constructor — a method that initializes a new object.
  • attribute — data stored inside an object.
  • method — a function defined inside a class.
  • object state — the current values of an object's attributes.
🧩 Collocations natural English
  • define a class
  • create an object
  • initialize an attribute
  • call a method
  • update the object state
  • reduce the stock quantity
🗣️ Phrasal Verbs interview speech
  • set up — “The constructor sets up the object's initial attributes.”
  • take away — “The sell method takes away units from the available stock.”
  • run out of — “The product could run out of stock.”
  • keep track of — “The object keeps track of its current quantity.”
🎤 Model Answer spoken

The Product class is a blueprint for inventory items. Each product object has a name and a quantity.

The __init__ method is the constructor. It runs when a new object is created and initializes the object's attributes. The parameter self refers to the current object.

The sell() method checks whether enough units are available. If the requested amount is less than or equal to the current quantity, it subtracts that amount and returns a success message. Otherwise, it returns "Not enough stock."

The laptop begins with five units. After selling two, three units remain. The outputs are Sold 2 units., Laptop: 3 units available, and Not enough stock.

Exercise 6 · Explain This Data-Processing Function (Sales Summary)

Python · Upper-Intermediate
Explain this code out loud. Focus on a list of dictionaries, aggregation, dictionary methods, conditional updates, and sorting with a lambda function.
def summarize_sales(transactions):
    totals = {}

    for transaction in transactions:
        product = transaction["product"]
        amount = transaction["amount"]

        if product not in totals:
            totals[product] = 0

        totals[product] += amount

    return sorted(
        totals.items(),
        key=lambda item: item[1],
        reverse=True
    )

sales = [
    {"product": "Keyboard", "amount": 120},
    {"product": "Mouse", "amount": 80},
    {"product": "Keyboard", "amount": 60},
    {"product": "Monitor", "amount": 250},
    {"product": "Mouse", "amount": 40}
]

print(summarize_sales(sales))
🎯 Instructions oral task
  1. Explain the structure of the transaction data.
  2. Explain why the totals dictionary starts empty.
  3. Describe how the product and amount are extracted.
  4. Explain the purpose of if product not in totals.
  5. Explain how repeated product values are combined.
  6. Describe what totals.items() returns.
  7. Explain how the lambda function selects the sort key.
  8. Explain the effect of reverse=True.
  9. State the final output.
📖 Vocabulary core
  • transaction — a record of a business activity or exchange.
  • aggregation — combining multiple values into a summary.
  • accumulator — a variable that stores a running total.
  • dictionary entry — one key-value pair inside a dictionary.
  • sort key — the value used to determine the order of items.
  • lambda function — a short anonymous function written in one expression.
  • descending order — an arrangement from the highest value to the lowest.
🧩 Collocations natural English
  • process transaction data
  • extract a field
  • initialize a total
  • accumulate sales amounts
  • group values by product
  • sort results in descending order
  • generate a sales summary
🗣️ Phrasal Verbs interview speech
  • add together — “The function adds together sales for the same product.”
  • group by — “The data is grouped by product name.”
  • build up — “The dictionary builds up a running total.”
  • sort out — “The final step sorts out the products by total sales.”
  • come out on top — “The monitor comes out on top because it has the highest total.”
🎤 Model Answer spoken

This function summarizes transaction data by calculating the total sales amount for each product. The input is a list of dictionaries, and each dictionary contains a product name and an amount.

The function starts with an empty dictionary called totals. During each iteration, it extracts the product and amount from the current transaction. If the product is not already a key in the dictionary, the function initializes its total to zero.

It then adds the transaction amount to the product's running total. This means repeated products are grouped together and their amounts are aggregated.

The items() method returns the dictionary entries as product-and-total pairs. The sorted() function orders these pairs. The lambda function uses the value at index one, which is the total amount, as the sort key. The argument reverse=True sorts the results from highest to lowest.

Keyboard totals 180, Mouse totals 120, and Monitor totals 250. Therefore, the final output is [('Monitor', 250), ('Keyboard', 180), ('Mouse', 120)].