Python by Projects › Function Factory

Exercises: Function Factory

Build, trace, repair, and design functions. Write and run notebook-safe Python in the blank cells, and write complete turtle programs in the assets/ folder. In a blank code cell, write sentence answers inside a complete print(...) line so Python can read them.

Exercise 1

Write a function named cheer with one parameter named name. Inside the function, build an f-string in a local variable named message, then return message. Call your function twice with two sample names. Store each returned value in a different variable outside the function and print both variables.

Before you run it, predict the two output lines. Explain why the caller uses the returned values instead of trying to print the function's local message directly.

Real program

Keep the fixed-data version. Then read first_name and second_name with two plain input() calls, call cheer once with each name, store the two returned values in separate outside variables, and print both variables.

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 2

This function call supplies a name, but the definition has no parameter to receive it. The broken code is shown as text. Repair it in the blank cell by adding the parameter, building the greeting in a local variable, and returning that local value. Store the returned value outside the function and print it, then explain what you changed.

def greeting_card():
    print(f"Welcome, {name}!")

greeting_card("Rin")

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 3

Compare these two functions without running them.

def show_double(number):
    print(number * 2)

def get_double(number):
    return number * 2

Which function lets another calculation reuse the doubled number? Explain the difference between print and return in your own words. Then author your own get_double(number) function: store number * 2 in a local variable named doubled, return it, and call it with 2.5. Store the returned float value in doubled_score, compose it into the f-string Doubling 2.5 gives 5.0., and print that message.

Real program

Keep the fixed-data version. Then read number with number = float(input(...)), calculate doubled_score = get_double(number), build double_message = f"Doubling {number} gives {doubled_score}.", and print double_message.

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 4

Write area(w, h). Inside the function, store w * h in a local variable named card_area, then return it. Call the function with w equal to 8 and h equal to 2.5. Store the returned value in a different variable outside the function, then use that outside variable in an f-string message.

Predict whether the returned result will be a whole-number value or a float value before running the cell.

Real program

Keep the fixed-data version. Then read both w and h with float(input(...)), call calculated_area = area(w, h), use calculated_area in the same f-string, and print the message, so 8.0 * 2.5 prints 20.0.

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 5

Trace this code on paper.

team = "Comets"

def player_label(name):
    label = f"{team}: {name}"
    print(label)

player_label("Jo")
print(team)

Predict the exact two output lines. Which name is global? Which name is local? Explain why print(label) would cause a NameError if it were added after the function call.

How this is checked: Checked by comparing your prediction with what the program really prints.

Answer format: several lines

Also check yourself

The automatic check cannot see these, so tick each one when your work does it.

For parents and teachers: report a problem

Exercise 6

Open assets/ex6_stamp_row.py. Its tiny warm-up square is valid starter code, not the finished program. Replace the warm-up with a row of four square stamps. You must author all of these parts yourself in the asset:

  • an import turtle statement;
  • a color-setting line and a pen-down line;
  • an outer for loop for the four stamps;
  • turtle.pensize(stamp_number + 1) inside that outer loop, so the loop counter controls each stamp's pen width;
  • an inner for loop for the four sides of each stamp;
  • forward and right calls that close every square; and
  • pen-up movement between stamps so the connecting path is not drawn.

Run the asset from the terminal. In the notebook cell below, write only a numeric proxy check: start side_moves at 0, loop over the four stamp_number values, calculate last_pen_size = stamp_number + 1, add 4 to side_moves on each turn, and print the final pen size and side-move count. They should be 4 and 16. Do not import or call turtle in the notebook.

Real program

Keep the fixed-data version. Then, for the notebook numeric proxy, read stamp_count with int(input(...)), loop with range(stamp_count), and run the unchanged side_moves and last_pen_size computation and two final print calls.

More Practice

How this is checked: You check this one yourself, against the list below. The turtle drawing is checked from the moves your program makes.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 7

This program raises a NameError because card_label is local to make_label, but the last line tries to use it outside the function. The broken program is text only; do not run it.

def make_label(name):
    card_label = f"Made for {name}"

make_label("Nia")
print(card_label)

Repair the program in the blank cell. Keep card_label local, return it from make_label, and have the caller store the returned value in a different variable before printing it. Then explain why the repaired final print can see the caller's variable.

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 8

Write turn_angle(n) so it returns 360 / n. Then write angle_message(angle) so it returns an f-string that includes the angle. Compose the functions by feeding the returned float value from turn_angle(7) directly into a call to angle_message. Store the final returned message and print it. Predict why the message contains a decimal value.

Both functions should return values rather than print inside their bodies. Name the local parameter in each function and explain how each returned value moves to the next part of the program.

Real program

Keep the fixed-data version. Then read n once with int(input(...)), pass that shared value through angle_message(turn_angle(n)), store the returned message in final_message, and print it.

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 9

Open assets/ex10_stamp_grid.py. Replace its warm-up square with a grid containing 3 rows and 4 columns of square stamps. Choose a size, then define stamp(size) to draw one closed square. In the asset, author an import turtle statement, a color-setting line, a pen-down line, the outer row for line, and the inner column for line. Call stamp(size) inside the inner loop. Use only forward, backward, left (left turns the other way), and right for movement and turns. Use pen-up movement between stamps and rows.

Also start stamps_drawn at 0, author stamps_drawn = stamps_drawn + 1 inside the inner loop, and print the final count. Run the asset from the terminal. In the notebook cell below, write only a non-turtle numeric proxy check: use the same nested loops and accumulator update, then print the final count. It should be 12.

Real program

Keep the fixed-data version. Then, for the notebook numeric proxy, read rows and columns with two int(input(...)) calls, use nested loops with range(rows) and range(columns), and run the unchanged count and final print(stamps_drawn).

How this is checked: You check this one yourself, against the list below. The turtle drawing is checked from the moves your program makes.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 10

Open assets/ex11_stamp_bands.py. Replace its warm-up square with 2 bands of 5 square stamps. Define or reuse stamp(size) from Exercise 9. In the asset, author an import turtle statement, a color-setting line, a pen-down line, an outer for line for the bands, and an inner for line for the stamps. Use the outer counter in size = 15 + band_number * 5 to change the stamp size. Use only forward, backward, left (left turns the other way), and right for movement and turns, with pen-up movement between stamps.

Start stamps_drawn at 0, author stamps_drawn = stamps_drawn + 1 inside the inner loop, and print the final count. Run the asset from the terminal. In the notebook cell below, write only a non-turtle numeric proxy check: use the same nested loops, size formula, and accumulator update, then print the final size and count. They should be 20 and 10.

Real program

Keep the fixed-data version. Then, for the notebook numeric proxy, read bands and stamps_per_band with two int(input(...)) calls, use loops with range(bands) and range(stamps_per_band), and run the unchanged size/count computation and its two final print calls.

How this is checked: You check this one yourself, against the list below. The turtle drawing is checked from the moves your program makes.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Algorithm Extension

Extra loop practice — optional enrichment: these drills reuse the same loop shapes on small fixed data, so try as many as you like.

Exercise 11

Write total_card_borders(number_of_cards). Inside the function, start a local variable named total at 0. Loop over range(number_of_cards). On each turn, calculate side = 10 + card_number * 5, calculate border_length = side * 4, then author the accumulator update total = total + border_length. Return the final total.

Call the function for 4 cards, store the returned value outside the function, and print it. Predict the total before running your code, and explain why the return line belongs after the loop.

Pattern Spotlight retrieval: Which pattern is this, and which variable is the total-so-far? Variation axis — packaging: inline home → function.

Real program

Keep the fixed-data version. Then read number_of_cards with int(input(...)), call border_total = total_card_borders(number_of_cards), and print border_total.

How this is checked: You check this one yourself, against the list below. The turtle drawing is checked from the moves your program makes.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 12: Count Bonus Stamps

Define count_bonus_stamps(n) with def, use for i in range(1, n + 1) and a counting accumulator to count the whole numbers from 1 through n inclusive that are multiples of 3, and return the count.

For example, count_bonus_stamps(10) returns 3 because the matching numbers are 3, 6, and 9.

Real program

Keep the fixed-data version. Then read n with int(input(...)) and print count_bonus_stamps(n).

How this is checked: Checked by tests that run your function count_bonus_stamps.

Also check yourself

The automatic check cannot see these, so tick each one when your work does it.

For parents and teachers: report a problem

Exercise 13: Total Even Stamps

Define total_even_stamps(n) with def, use for i in range(1, n + 1) and a running-total accumulator to add the even numbers from 1 through n inclusive, and return the total.

For example, total_even_stamps(6) returns 12 because 2 + 4 + 6 = 12.

Real program

Keep the fixed-data version. Then read n with int(input(...)) and print total_even_stamps(n).

How this is checked: Checked by tests that run your function total_even_stamps.

Also check yourself

The automatic check cannot see these, so tick each one when your work does it.

For parents and teachers: report a problem

Exercise 14: Stamps in a Triangle

Define stamps_in_triangle(rows) with def, use for i in range(1, rows + 1) and a running-total accumulator to add 1 + 2 + ... + rows, and return the total.

For example, stamps_in_triangle(5) returns 15 because 1 + 2 + 3 + 4 + 5 = 15.

Real program

Keep the fixed-data version. Then read rows with int(input(...)) and print stamps_in_triangle(rows).

How this is checked: Checked by tests that run your function stamps_in_triangle.

Also check yourself

The automatic check cannot see these, so tick each one when your work does it.

For parents and teachers: report a problem

Exercise 15: Average Side Length

Define average_side(n) with def, use for i in range(1, n + 1) and a running-total accumulator to add the side lengths from 1 through n, divide the total by n, and return the floating-point average.

For example, average_side(4) returns 2.5.

Real program

Keep the fixed-data version. Then read n with int(input(...)) and print average_side(n).

How this is checked: Checked by tests that run your function average_side.

Also check yourself

The automatic check cannot see these, so tick each one when your work does it.

For parents and teachers: report a problem

Exercise 16: Check Before You Add

Define both stamps_that_fit(limit) and width_used(limit) with def; in each function, use for i in range(5) to calculate size = 10 + 5 * i and track a running width and count, then make stamps_that_fit return how many stamps were added and width_used return the final running width.

This is the check-before-adding rule—"check before you add"—and it contrasts with Exercise 17's add-then-check rule using the same stamp sizes: add a stamp only when the new width would stay <= limit; otherwise stop the loop entirely instead of skipping it and continuing.

At limit = 60, stamps_that_fit(60) returns 3 and width_used(60) returns 45 because 10, 15, and 20 fit for a total of 45, but adding 25 would make 70, which exceeds 60, so the loop stops there. Both functions use the same loop over the sizes; only the value you return differs.

Real program

Keep the fixed-data version. Then read the shared limit once with int(input(...)) and print both stamps_that_fit(limit) and width_used(limit).

How this is checked: Checked by tests that run your functions stamps_that_fit, width_used.

Also check yourself

The automatic check cannot see these, so tick each one when your work does it.

For parents and teachers: report a problem

Exercise 17: Add First, Then Check

Define both stamps_to_pass(limit) and width_when_passed(limit) with def; in each function, use for i in range(5) to calculate size = 10 + 5 * i and track a running width and count, then make stamps_to_pass return how many stamps were added including the one that pushed the width over and width_when_passed return the final running width including that last stamp.

This is the add-then-check rule—"add first, then check"—the opposite boundary rule from Exercise 16's check-before-adding rule using the same stamp sizes: add each stamp's width first, count that stamp, and then stop as soon as the running width exceeds limit.

At limit = 60, stamps_to_pass(60) returns 4 and width_when_passed(60) returns 70 because 10 + 15 + 20 = 45 is still <= 60, so the loop keeps going, then adding 25 makes 70, which exceeds 60, so it stops there after adding 4 stamps. Both functions use the same loop over the sizes; only the value you return differs.

Real program

Keep the fixed-data version. Then read the shared limit once with int(input(...)) and print both stamps_to_pass(limit) and width_when_passed(limit).

How this is checked: Checked by tests that run your functions stamps_to_pass, width_when_passed.

Also check yourself

The automatic check cannot see these, so tick each one when your work does it.

For parents and teachers: report a problem

Exercise 18: Reach the Target

For this sentinel-loop drill, define stamps_to_reach(target) with def and a while loop—not a for loop—and repeatedly add the fixed width 5 to a running total until that total reaches or exceeds target, then return how many stamps were added.

For example, stamps_to_reach(30) returns 6.

Real program

Keep the fixed-data version. Then read target with int(input(...)) and print stamps_to_reach(target).

How this is checked: Checked by tests that run your function stamps_to_reach.

Also check yourself

The automatic check cannot see these, so tick each one when your work does it.

For parents and teachers: report a problem

Exercise 19: Count Jumbo Stamps (Homework)

Define count_jumbo_stamps(n, threshold) with def, use for i in range(1, n + 1) and a counting accumulator to count the whole numbers from 1 through n inclusive that are greater than or equal to threshold, and return the count.

For example, count_jumbo_stamps(10, 7) returns 4 because the matching numbers are 7, 8, 9, and 10.

Real program

Keep the fixed-data version. Then read both n and threshold with separate int(input(...)) calls and print count_jumbo_stamps(n, threshold).

How this is checked: Checked by tests that run your function count_jumbo_stamps.

Also check yourself

The automatic check cannot see these, so tick each one when your work does it.

For parents and teachers: report a problem

Exercise 20: Total Ribbon (Homework)

Define total_ribbon(n, start, growth) with def, use for i in range(n) and a running-total accumulator to add the n terms of an arithmetic sequence where the first term is start and each next term is growth larger than the previous term, and return the total.

For example, total_ribbon(4, 10, 5) returns 70 because 10 + 15 + 20 + 25 = 70.

Real program

Keep the fixed-data version. Then read n, start, and growth with three separate int(input(...)) calls and print total_ribbon(n, start, growth).

How this is checked: Checked by tests that run your function total_ribbon.

Also check yourself

The automatic check cannot see these, so tick each one when your work does it.

For parents and teachers: report a problem

Challenge

Try these after the earlier exercises.

Challenge 1

  • Challenge

Build a name-badge factory. Define name_badge(name, club) with two parameters. It should print a pen-stroke-style border made from text symbols and an f-string containing both values. Call it twice with sample values and predict the output first.

Real program

Keep the fixed-data version. Then use four plain input() reads for first_name, first_club, second_name, and second_club, followed by the two bare calls name_badge(first_name, first_club) and name_badge(second_name, second_club).

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Challenge 2

  • Challenge

Plan a flower stamp without recursion: flower must call petal inside a loop, and neither function may call itself. Complete the written plan and predict how many petals one call draws. Keep it in this markdown fence; do not run turtle here.

def petal(size):
    ____

def flower(size, petal_count):
    for petal_number in range(petal_count):
        ____
        turtle.right(360 / petal_count)

How this is checked: You check this one yourself, against the list below. The turtle drawing is checked from the moves your program makes.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Back to Function Factory