Book-matched resources · Chapter 06 · Challenges 051–060

Functions and Reusable Code

Try the printed challenge before revealing a hint or the example solution. Starter files are available only where the book supplies one.

Challenge hints & worked solutions

CHALLENGE 051 · BUILD IT

A Friendly Greeting Function

Write a reusable function called greet(name). It must receive a name and return a friendly message. Call it with two different names and print the results; avoid putting print() inside the function.

Start from a blank Python file; no starter supplied for this challenge.Download worked solution .py ↓
Reveal a hint (from the printed book)

Write def greet(name):, then return an f-string. Use the return value in print() outside the function.

Reveal a worked Python solution

One possible implementation. Check the book's tests and try an extension after comparing.

# Challenge 51 - A Friendly Greeting Function
def greet(name):
    return f"Hello, {name.strip()}!"

print(greet("Alex"))
print(greet("Riley"))
Save this Python file ↓
CHALLENGE 052 · BUILD IT

Currency Practice Converter

Create a classroom-only converter from fictional practice dollars to pounds. For this problem, use a fixed example rate: 1 practice dollar = £0.80. This is NOT a live exchange rate.

Start from a blank Python file; no starter supplied for this challenge.Download worked solution .py ↓
Reveal a hint (from the printed book)

Use a named constant such as PRACTICE_RATE = 0.80 and multiply the input amount. Format only at display time.

Reveal a worked Python solution

One possible implementation. Check the book's tests and try an extension after comparing.

# Challenge 52 - Currency Practice Converter
# Fictional classroom exchange rate, NOT today's market rate.
PRACTICE_RATE = 0.80

def to_pounds(practice_dollars):
    return practice_dollars * PRACTICE_RATE

for amount in (10, 2.5):
    print(f"{amount:g} practice dollars = £{to_pounds(amount):.2f}")
Save this Python file ↓
CHALLENGE 053 · IMPROVE IT

Reusable Tax Calculator

The starter program calculates two item prices using the same hypothetical 20% tax calculation. Refactor the repeated arithmetic into one reusable function. The rate is a classroom example, not tax guidance.

Reveal a hint (from the printed book)

Move net * (1 + rate) into a function, then call it for both items. Check that 0 remains 0.

Reveal a worked Python solution

One possible implementation. Check the book's tests and try an extension after comparing.

# Challenge 53 - Reusable Tax Calculator
# A hypothetical 20% practice tax rate.
def total_with_tax(net, rate=0.20):
    return round(net * (1 + rate), 2)

print(f"Item A: £{total_with_tax(50):.2f}")
print(f"Item B: £{total_with_tax(12.50):.2f}")
Save this Python file ↓
CHALLENGE 054 · BUILD IT

Reusable Ticket Formatter

Create a function that formats a ticket using a name, event and ticket type. The function must return a string so another part of the program can print it, save it or send it elsewhere.

Start from a blank Python file; no starter supplied for this challenge.Download worked solution .py ↓
Reveal a hint (from the printed book)

The function needs three parameters and a return statement. Use an f-string to add labels and separators.

Reveal a worked Python solution

One possible implementation. Check the book's tests and try an extension after comparing.

# Challenge 54 - Reusable Ticket Formatter
def format_ticket(name, event, ticket_type):
    return f"Name: {name} | Event: {event} | Type: {ticket_type}"

example = format_ticket("Alex", "Code Club", "Standard")
print(example)
Save this Python file ↓
CHALLENGE 055 · SOLVE IT

Score to Badge Function

Design a function that awards a coding badge for scores from 0 to 100. Use these bands: 0–39 Starter; 40– 69 Builder; 70–89 Developer; 90–100 Expert. Return Invalid score outside 0–100.

Start from a blank Python file; no starter supplied for this challenge.Download worked solution .py ↓
Reveal a hint (from the printed book)

Check invalid scores first; then compare against the next boundary (40, 70, 90) in order.

Reveal a worked Python solution

One possible implementation. Check the book's tests and try an extension after comparing.

# Challenge 55 - Score to Badge Function
def badge_for(score):
    if not isinstance(score, int) or not 0 <= score <= 100:
        return "Invalid score"
    if score < 40:
        return "Starter"
    if score < 70:
        return "Builder"
    if score < 90:
        return "Developer"
    return "Expert"

for score in (0, 39, 40, 70, 90, 100):
    print(f"{score}: {badge_for(score)}")
Save this Python file ↓
CHALLENGE 056 · DEBUG IT

Passphrase Rules Checker

The faulty function accepts practice passphrases when only one rule is met. Repair it so all three conditions must hold: at least 10 characters, at least one digit, and no spaces. Never use a real password for this exercise.

Reveal a hint (from the printed book)

Use and between all three requirements. any(character.isdigit() for character in phrase) checks digits.

Reveal a worked Python solution

One possible implementation. Check the book's tests and try an extension after comparing.

# Challenge 56 - Passphrase Rules Checker
# Simplified practice rules, not a complete password-security test.
def valid_phrase(phrase):
    long_enough = len(phrase) >= 10
    has_digit = any(character.isdigit() for character in phrase)
    no_spaces = " " not in phrase
    return long_enough and has_digit and no_spaces

phrase = input("Enter a practice passphrase: ")
print("Accepted" if valid_phrase(phrase) else "Rejected")
Save this Python file ↓
CHALLENGE 057 · IMPROVE IT

Minutes and Seconds Formatter

The starter calculates minutes with ordinary division and does not check negative durations. Fix it so an integer number of seconds becomes minutes:seconds, with the seconds part always two digits.

Reveal a hint (from the printed book)

Use seconds // 60 for whole minutes and seconds % 60 for the remainder. :02d pads to two digits.

Reveal a worked Python solution

One possible implementation. Check the book's tests and try an extension after comparing.

# Challenge 57 - Minutes and Seconds Formatter
def format_duration(seconds):
    if seconds < 0:
        return "Invalid duration"
    minutes = seconds // 60
    remainder = seconds % 60
    return f"{minutes}:{remainder:02d}"

for seconds in (0, 9, 125, 3600, -1):
    print(f"{seconds}: {format_duration(seconds)}")
Save this Python file ↓
CHALLENGE 058 · BUILD IT

Remove Repeated Code

A club report repeats the same print structure three times. Replace it with a single function that accepts a club name and a number of participants. Use the printed starter as your starting point.

Reveal a hint (from the printed book)

Turn repeated output into def show_report(club, members): and call it three times.

Reveal a worked Python solution

One possible implementation. Check the book's tests and try an extension after comparing.

# Challenge 58 - Remove Repeated Code
def show_report(club, members):
    print(f"{club}: {members} participants")

show_report("Reading", 12)
show_report("Coding", 8)
show_report("Robotics", 5)
Save this Python file ↓
CHALLENGE 059 · DEBUG IT

Test Your Functions

The provided tests always pass because they compare hard-coded numbers instead of calling double(). Repair them so they actually verify the function. Then deliberately break the function to prove your tests catch the mistake.

Reveal a hint (from the printed book)

The expression inside each assert must actually call double(...). Try changing the function to *3 briefly.

Reveal a worked Python solution

One possible implementation. Check the book's tests and try an extension after comparing.

# Challenge 59 - Test Your Functions
def double(number):
    return number * 2

assert double(4) == 8
assert double(0) == 0
assert double(-3) == -6
print("All tests passed")
Save this Python file ↓
CHALLENGE 060 · SOLVE IT

Build a Quiz Engine

Build a short programming quiz using reusable functions for asking questions, checking an answer and reporting the score. Store questions and their correct answers together so you can replace them without rewriting the scoring code.

Start from a blank Python file; no starter supplied for this challenge.Download worked solution .py ↓
Reveal a hint (from the printed book)

Break the task into ask_question(), mark_answer(), run_quiz() and show_result(); store question– answer pairs in a list.

Reveal a worked Python solution

One possible implementation. Check the book's tests and try an extension after comparing.

# Challenge 60 - Build a Quiz Engine
def ask_question(prompt):
    return input(prompt + " ").strip().casefold()

def mark_answer(response, expected):
    return response.strip().casefold() == expected.strip().casefold()

def run_quiz(question_set):
    score = 0
    for question, answer in question_set:
        correct = mark_answer(ask_question(question), answer)
        print("Correct!" if correct else "Not quite.")
        if correct:
            score += 1
    return score

def show_result(score, total):
    print(f"Score: {score}/{total}")

questions = [("Keyword to define a function?", "def"),
             ("Keyword to send back a result?", "return")]
show_result(run_quiz(questions), len(questions))
Save this Python file ↓