---
title: "Functions"
book: "Primary & Middle School Computer Science"
subject: computer-science
language: en
chapter: 19
exercises: 12
source: https://one-course.com/books/computer-science/1/en/chapter/19-functions
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 19 — Functions

Lina’s family is repainting the house, and her [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) computes the area of each of the five rooms: the same three lines, copied five times with other numbers. Then she notices a mistake in those three lines. Now she must correct it five times, and hope she has not missed one. If the three lines had a name, she could write them once and use them five times, and a mistake would be fixed in one place.

**You already know.**

A [variable](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) is a name for a [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) ([Chapter 15](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#ch-g6-variables-and-input)); `print` shows a [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) on the screen ([Chapter 14](https://one-course.com/books/computer-science/1/en/chapter/14-a-first-python-program#ch-g6-first-python-program)); `if` chooses between blocks ([Chapter 17](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#ch-g6-if-else)).

## 19.1 Defining and calling a function

**Definition 19.1 (Function and function call).**

A *function* is a block of [instructions](https://one-course.com/books/computer-science/1/en/chapter/2-instructions-in-order#def-g1-instructions-in-order-instruction) with a name, written once and run whenever it is needed. It is *defined* with `def`, the name, brackets and a colon, followed by an indented block, its *body*. A *function call* is the name followed by brackets: it runs the body.

```python
def say_hello():
    print("Hello!")
    print("Welcome to the club.")


print("Before the calls")
say_hello()
say_hello()
say_hello()
```

***Listing 19.1.** A [function](#def-g7-functions-function) defined once and called three times. code/grade-7/01-functions/listings/greet.py*

```
$ python greet.py
Before the calls
Hello!
Welcome to the club.
Hello!
Welcome to the club.
Hello!
Welcome to the club.
```

***Output 19.1.** The body ran three times, once for each call.*

Lines 1 to 3 only *define* the [function](#def-g7-functions-function): Python remembers it and prints nothing. That is why `Before the calls` comes first. A [function](#def-g7-functions-function) runs only when it is called. Two empty lines after a [function](#def-g7-functions-function) are the custom in Python: they make each [function](#def-g7-functions-function) easy to see.

## 19.2 Parameters and arguments

Most [functions](#def-g7-functions-function) need [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) to work on. The area of a room needs its width and its length.

**Definition 19.2 (Parameter and argument).**

A *parameter* is a [variable](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) named between the brackets of a [function](#def-g7-functions-function)’s definition. An *argument* is the [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) given for it in a call: in `area(3, 4)`, the parameter `width` takes the argument 3, and `length` takes 4.

**Definition 19.3 (Return value).**

The [instruction](https://one-course.com/books/computer-science/1/en/chapter/2-instructions-in-order#def-g1-instructions-in-order-instruction) `return` ends the call and gives a [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) back to the place where the [function](#def-g7-functions-function) was called: the *return value*. The call can then be used like that [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value), in a calculation or an [assignment](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-assignment).

```python
def area(width, length):
    return width * length


kitchen = area(3, 4)
print("Kitchen:", kitchen)
print("Bedroom:", area(3.5, 4))
print("Both:", kitchen + area(3.5, 4))
```

***Listing 19.2.** A [function](#def-g7-functions-function) with two [parameters](#def-g7-functions-parameter) and a [return value](#def-g7-functions-return-value). code/grade-7/01-functions/listings/area.py*

```
$ python area.py
Kitchen: 12
Bedroom: 14.0
Both: 26.0
```

***Output 19.2.** Each call is replaced by the [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) it returns.*

![A function is like a machine: the arguments go in through the parameters, and the return value comes out.](https://one-course.com/images/onecourse/chapters/computer-science-1/g7-functions/fig-fcabdadae9d3.svg)

*A [function](#def-g7-functions-function) is like a machine: the [arguments](#def-g7-functions-parameter) go in through the [parameters](#def-g7-functions-parameter), and the [return value](#def-g7-functions-return-value) comes out.*

[Arguments](#def-g7-functions-parameter) are given to [parameters](#def-g7-functions-parameter) in order: the first [argument](#def-g7-functions-parameter) to the first [parameter](#def-g7-functions-parameter), and so on. Swapping them is not an error for Python, but the result is wrong:

```python
def introduce(name, age):
    print(f"{name} is {age} years old.")


introduce("Noor", 11)
introduce(11, "Noor")     # the arguments in the wrong order
```

***Listing 19.3.** The order of the [arguments](#def-g7-functions-parameter). code/grade-7/01-functions/listings/two_params.py*

```
$ python two_params.py
Noor is 11 years old.
11 is Noor years old.
```

***Output 19.3.** The second call gave 11 to `name` and `"Noor"` to `age`.*

A [function](#def-g7-functions-function) can call another [function](#def-g7-functions-function). Here, `largest3` finds the largest of three numbers with two calls to `largest2`. A `return` inside an `if` ends the call at once, so line 4 runs only when `a > b` is false.

```python
def largest2(a, b):
    if a > b:
        return a
    return b


def largest3(a, b, c):
    return largest2(largest2(a, b), c)


print(largest2(4, 9))
print(largest3(4, 9, 2))
print(largest3(7, 3, 5))
```

***Listing 19.4.** A [function](#def-g7-functions-function) built from another. code/grade-7/01-functions/listings/largest.py*

```
$ python largest.py
9
9
7
```

***Output 19.4.** The largest of 4 and 9; of 4, 9 and 2; of 7, 3 and 5.*

![The journey of a call. The caller waits while largest3 runs; largest3 itself waits for each call to largest2. Each value comes back to the place where its call was written.](https://one-course.com/images/onecourse/chapters/computer-science-1/g7-functions/fig-1f2922b0abc4.svg)

*The journey of a call. The caller waits while `largest3` runs; `largest3` itself waits for each call to `largest2`. Each [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) comes back to the place where its call was written.*

## 19.3 `return` is not `print`

`print` shows a [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) to the person in front of the screen. `return` gives a [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) to the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program). A [function](#def-g7-functions-function) that prints its result instead of returning it shows the right number, but the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) cannot use it:

```python
def area(width, length):
    print(width * length)     # shows the area, but gives nothing back


total = area(3, 4) + 1
print(total)
```

***Listing 19.5.** Printing instead of returning. code/grade-7/01-functions/listings/print_not_return.py*

```
$ python print_not_return.py
12
Traceback (most recent call last):
  File "~/session/print_not_return.py", line 5, in <module>
    total = area(3, 4) + 1
            ~~~~~~~~~~~^~~
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
[exit status 1]
```

***Output 19.5.** 12 is shown, then the addition fails.*

A [function](#def-g7-functions-function) without `return` gives back the special [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) `None`, which means “nothing”. Adding 1 to nothing makes no sense: the [error message](https://one-course.com/books/computer-science/1/en/chapter/14-a-first-python-program#def-g6-first-python-program-error) names the type of `None`, `NoneType`. The rule of thumb: a [function](#def-g7-functions-function) that *computes* something returns it, and the caller decides whether to print it.

## 19.4 Local variables

**Definition 19.4 (Local variable).**

A *local variable* is a [variable](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) created inside a [function](#def-g7-functions-function): a [parameter](#def-g7-functions-parameter), or a name assigned in the body. It exists only while the call runs, and the rest of the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) cannot see it.

```python
def area(width, length):
    result = width * length
    return result


print(area(3, 4))
print(result)
```

***Listing 19.6.** A [local variable](#def-g7-functions-local-variable) used outside its [function](#def-g7-functions-function). code/grade-7/01-functions/listings/local.py*

```
$ python local.py
12
Traceback (most recent call last):
  File "~/session/local.py", line 7, in <module>
    print(result)
          ^^^^^^
NameError: name 'result' is not defined
[exit status 1]
```

***Output 19.6.** `result` was local to `area`: after the call, it is gone.*

![Local boxes appear when the call starts and disappear when it returns. Only the return value, 12, survives.](https://one-course.com/images/onecourse/chapters/computer-science-1/g7-functions/fig-8f5899ab21a0.svg)

*Local boxes appear when the call starts and disappear when it returns. Only the [return value](#def-g7-functions-return-value), 12, survives.*

[Local variables](#def-g7-functions-local-variable) are a good thing: a [function](#def-g7-functions-function) can use any names it likes without spoiling the [variables](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) of the rest of the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program), and two [functions](#def-g7-functions-function) can both have a [variable](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) called `total` without mixing them up.

## 19.5 Cutting a problem into functions

A long task is easier to write, read and correct when it is cut into small [functions](#def-g7-functions-function), each with one job. This receipt printer has three: one computes the price of a line, one prints a line, and one prints the whole receipt.

```python
def line_total(price, quantity):
    return price * quantity


def show_line(name, price, quantity):
    total = line_total(price, quantity)
    print(f"{name:10} {quantity} x {price:5.2f} = {total:6.2f}")
    return total


def receipt():
    total = 0
    total = total + show_line("bread", 1.80, 2)
    total = total + show_line("apples", 0.45, 6)
    total = total + show_line("milk", 1.10, 3)
    print(f"{'TOTAL':22} {total:6.2f}")


receipt()
```

***Listing 19.7.** A receipt in three [functions](#def-g7-functions-function). code/grade-7/01-functions/listings/receipt.py*

```
$ python receipt.py
bread      2 x  1.80 =   3.60
apples     6 x  0.45 =   2.70
milk       3 x  1.10 =   3.30
TOTAL                    9.60
```

***Output 19.7.** The receipt; the columns line up.*

In the f-strings, the sign `:` after a [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) gives its layout: `:10` gives a text 10 places, and `:5.2f` writes a number 5 places wide with 2 decimals.

`show_line` prints, which seems to break the rule of thumb above. Printing a line is its job, and it also returns the line’s total, so that `receipt` can add the totals up.

![Who calls whom in .](https://one-course.com/images/onecourse/chapters/computer-science-1/g7-functions/fig-9f5fb5f38514.svg)

*Who calls whom in [Listing 19.7](#lst-g7-functions-receipt).*

Each [function](#def-g7-functions-function) should be checked before it is used by the others. The method: work out a few answers by hand, then call the [function](#def-g7-functions-function) with the same [arguments](#def-g7-functions-parameter) and compare. Choose examples that reach every branch, and the special cases (zero, two equal numbers).

```python
def area(width, length):
    return width * length


def largest2(a, b):
    if a > b:
        return a
    return b


# Each answer is worked out by hand first, then compared with the call.
print("expected 12, got", area(3, 4))
print("expected 0, got", area(0, 7))
print("expected 9, got", largest2(4, 9))
print("expected 9, got", largest2(9, 4))
print("expected 5, got", largest2(5, 5))
```

***Listing 19.8.** Checking two [functions](#def-g7-functions-function) on examples. code/grade-7/01-functions/listings/check_examples.py*

```
$ python check_examples.py
expected 12, got 12
expected 0, got 0
expected 9, got 9
expected 9, got 9
expected 5, got 5
```

***Output 19.8.** Every answer agrees.*

**Remark 19.5 (Programs that are also toolboxes).**

A [file](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-file) of [functions](#def-g7-functions-function) can be used by another [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program), which takes its [functions](#def-g7-functions-function) with `from area import area`, as we took `forward` from `turtle`. The lines of the [file](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-file) that are not in a [function](#def-g7-functions-function) then run as well, which is not wanted. Python programmers therefore put them under `if __name__ == "__main__":`. Those lines run when the [file](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-file) itself is run, and not when another [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) takes its [functions](#def-g7-functions-function):

```python
def area(width, length):
    return width * length


if __name__ == "__main__":
    print(area(3, 4))
```

***Listing 19.9.** The main part of a [file](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-file), guarded. code/grade-7/01-functions/listings/guarded.py*

```
$ python guarded.py
12
```

***Output 19.9.** Run directly, the [file](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-file) prints its example.*

## 19.6 Exercises

**Exercise 19.1 ★.**

What does this [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) print?

```python
def shout(word):
    print(word + "!")


shout("Hello")
print("between")
shout("Bye")
```

***Listing 19.10.** Two calls. code/grade-7/01-functions/exercises/two_calls.py*

**Solution of Exercise 19.1.**

`Hello!`, then `between`, then `Bye!`: the body of `shout` runs at each call, in the order of the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program).

**Exercise 19.2 ★.**

With `def f(x): return 2 * x + 1`, what does `print(f(2) + f(3))` print?

**Solution of Exercise 19.2.**

$f(2) = 5$ and $f(3) = 7$, so it prints 12.

**Exercise 19.3 ★.**

What appears on the screen?

```python
def double(n):
    print("doubling", n)
    return 2 * n


result = double(5)
print(result + 1)
```

***Listing 19.11.** Printing and returning. code/grade-7/01-functions/exercises/print_and_return.py*

**Solution of Exercise 19.3.**

`doubling 5`, printed during the call, then `11`: the call returned 10, kept in `result`, and 1 was added.

**Exercise 19.4 ★.**

Write a [function](#def-g7-functions-function) `perimeter(width, height)` that returns the perimeter of a rectangle.

**Solution of Exercise 19.4.**

```python
def perimeter(width, height):
    return 2 * (width + height)


print(perimeter(3, 4))
print(perimeter(10, 0.5))
```

*The perimeter of a rectangle. code/grade-7/01-functions/exercises/perimeter.py*

It prints 14 and 21.0.

**Exercise 19.5 ★★.**

Tom’s [function](#def-g7-functions-function) `average(a, b)` ends with `print((a + b) / 2)`. His [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) then does `print(average(8, 12) * 2)` and stops with a `TypeError`. Explain, and fix the [function](#def-g7-functions-function).

**Solution of Exercise 19.5.**

`average` prints the average but returns nothing, so `average(8, 12)` is `None`, and `None * 2` is refused. Replace the `print` by `return (a + b) / 2`; the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) then prints 20.0.

**Exercise 19.6 ★★.**

With the [function](#def-g7-functions-function) `area` of [Listing 19.2](#lst-g7-functions-area), Noor calls `area(4, 3)` for a room 3 wide and 4 long. Is the answer wrong? Now take `introduce` of [Listing 19.3](#lst-g7-functions-two-params): why does the order matter there and not for `area`?

**Solution of Exercise 19.6.**

No: `area(4, 3)` gives 12, like `area(3, 4)`, because $4 \times 3 = 3
\times 4$. For `introduce`, the two [parameters](#def-g7-functions-parameter) play different parts in the sentence, so swapping the [arguments](#def-g7-functions-parameter) gives a wrong sentence. The order of the [arguments](#def-g7-functions-parameter) always decides which [parameter](#def-g7-functions-parameter) gets which [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value); it only happens not to change the result of `area`.

**Exercise 19.7 ★★.**

Write a [function](#def-g7-functions-function) `is_even(n)` that returns `True` or `False`.

**Solution of Exercise 19.7.**

```python
def is_even(n):
    return n % 2 == 0


print(is_even(10), is_even(7), is_even(0))
```

*A [function](#def-g7-functions-function) that returns a [Boolean value](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison). code/grade-7/01-functions/exercises/is_even.py*

The [comparison](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison) is itself `True` or `False`: no `if` is needed. It prints `True False True`.

**Exercise 19.8 ★★.**

Write a [function](#def-g7-functions-function) `minutes_to_hours(m)` that returns a number of minutes in hours (90 gives 1.5) and prints nothing.

**Solution of Exercise 19.8.**

```python
def minutes_to_hours(m):
    return m / 60


print(minutes_to_hours(90))
print(minutes_to_hours(45) + minutes_to_hours(15))
```

*Minutes into hours. code/grade-7/01-functions/exercises/minutes_to_hours.py*

Because it returns its [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value), the results can be added: $0.75 + 0.25 = 1.0$.

**Exercise 19.9 ★★.**

How many times does the body of `square` run? What does the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) print?

```python
def square(n):
    print("computing", n)
    return n * n


total = 0
for i in range(1, 5):
    total = total + square(i)
print(total)
```

***Listing 19.12.** A call inside a [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop). code/grade-7/01-functions/exercises/loop_calls.py*

**Solution of Exercise 19.9.**

4 times, once for each turn of the [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop): it prints `computing 1` to `computing 4`, then $1 + 4 + 9 + 16 = 30$.

**Exercise 19.10 ★★★.**

Write a [function](#def-g7-functions-function) `price(age)` that returns the cinema ticket price of [Listing 17.3](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#lst-g6-if-else-ticket), and check it on the four ages of [Listing 17.7](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#lst-g6-if-else-boundaries).

**Solution of Exercise 19.10.**

Each branch returns its price, so the [function](#def-g7-functions-function) ends as soon as a case matches.

```python
def price(age):
    if age < 12:
        return 5
    elif age < 65:
        return 9
    else:
        return 6


for age in [11, 12, 64, 65]:
    print(age, price(age))
```

*The ticket price as a [function](#def-g7-functions-function). code/grade-7/01-functions/exercises/price.py*

It prints 5, 9, 9 and 6 for 11, 12, 64 and 65.

**Exercise 19.11 ★★★.**

To check `largest3` of [Listing 19.4](#lst-g7-functions-largest), which calls would you make so that the largest number is once in each of the three places? Add the cases with equal numbers. How many calls is that, at least?

**Solution of Exercise 19.11.**

Three calls put the largest number in each place: `largest3(9, 2, 4)`, `largest3(2, 9, 4)` and `largest3(2, 4, 9)`, all expected to give 9. They reach both branches of each call to `largest2`. Then the equal cases: `largest3(5, 5, 1)`, `largest3(1, 5, 5)`, `largest3(5, 1, 5)` and `largest3(5, 5, 5)`, all expected to give 5. That makes at least seven calls.

**Exercise 19.12 ★★★.**

Write a [function](#def-g7-functions-function) `digit_sum(n)` that returns the sum of the digits of `n`, and check it on five examples worked out by hand first.

**Solution of Exercise 19.12.**

```python
def digit_sum(n):
    total = 0
    while n > 0:
        total = total + n % 10
        n = n // 10
    return total


# expected values worked out by hand
print("expected 10, got", digit_sum(2026))
print("expected 0, got", digit_sum(0))
print("expected 7, got", digit_sum(7))
print("expected 1, got", digit_sum(1000))
print("expected 45, got", digit_sum(123456789))
```

*The digit sum, checked on five examples. code/grade-7/01-functions/exercises/digit_sum.py*

The examples cover an ordinary number, zero (the [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) does not run at all), a single digit, zeros inside a number, and a long number.

## 19.7 Problem: The Check Digit of a Barcode

**Problem 19.1.**

Weekend problem — catching typing mistakes

The 13-digit number under a barcode ends with a *check digit*. It is chosen so that the *weighted sum* of the 13 digits is a multiple of 10: counting from the right, the digits are multiplied by 1, 3, 1, 3, … in turn, and the products are added. A cashier who types a number with a mistake usually gets a weighted sum that is not a multiple of 10, and the till refuses it.

**Part I — By hand.** The number `5901234123457` is a valid example.

1. Compute its weighted sum. Is it a multiple of 10?
2. The first twelve digits of another number are `400638133393` . Find its check digit.
3. The cashier types `5901234123487` : one digit is wrong. Show that the till refuses it.
4. Why is the weight of the check digit 1, and not 3, convenient for computing it?

**Part II — Functions.** The number is kept as a whole number; its digits are taken off from the right with `% 10` and `// 10`. The text in triple quotes under a `def` line is a *docstring*: a sentence that says what the [function](#def-g7-functions-function) does.

```python
def weighted_sum(code):
    """The digits of code, from the right, times 1, 3, 1, 3, ..."""
    total = 0
    weight = 1
    while code > 0:
        total = total + weight * (code % 10)
        code = code // 10
        weight = 4 - weight          # 1 becomes 3, 3 becomes 1
    return total


def check_digit(first12):
    """The digit that makes the weighted sum of the 13 digits a multiple of 10."""
    return (10 - weighted_sum(first12 * 10) % 10) % 10


def is_valid(code):
    return weighted_sum(code) % 10 == 0


if __name__ == "__main__":
    print(weighted_sum(5901234123457))
    print(check_digit(590123412345))
    print(is_valid(5901234123457), is_valid(5901234123458))
```

***Listing 19.13.** Three [functions](#def-g7-functions-function) on barcode numbers. code/grade-7/01-functions/listings/barcode.py*

5. In `weighted_sum` , explain line 8: why does `4 - weight` switch between 1 and 3?
6. In `check_digit` , why multiply `first12` by 10 before computing the weighted sum? Why is there a second `% 10` at the end?
7. Check `check_digit` on your answer to question 2, and `is_valid` on the numbers of questions 1 and 3.
8. Write down how you would check `check_digit` on examples, in the style of [Listing 19.8](#lst-g7-functions-check) .

**Part III — Which mistakes are caught?**

```python
from barcode import is_valid

code = 5901234123457
caught = 0
changes = 0
place = 1                            # 1, 10, 100, ...: the place of a digit
for _ in range(13):
    digit = code // place % 10
    for new in range(10):
        if new != digit:
            changes = changes + 1
            wrong = code + (new - digit) * place
            if not is_valid(wrong):
                caught = caught + 1
    place = place * 10
print(caught, "caught out of", changes)
```

***Listing 19.14.** Every one-digit change of a valid number. code/grade-7/01-functions/listings/one_digit.py*

9. How many numbers does [Listing 19.14](#lst-g7-functions-one-digit) try? Run it: how many are refused?
10. Explain why changing one digit with weight 3 always changes the weighted sum by an amount that is not a multiple of 10.
11. Another common mistake is to swap two neighbouring digits. One of them has weight 1 and the other weight 3. If they are $a$ and $b$ , by how much does the weighted sum change?
12. The [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) `swaps.py` tries all 90 pairs of different digits $a,  b$. Run it: how many swaps are caught, and which are missed? `# Two neighbouring digits a, b (weights 1 and 3) swapped to b, a. caught = 0 for a in range (10 ): for b in range (10 ): if a != b: change = (b * 1 + a * 3 ) - (a * 1 + b * 3 ) if change % 10 != 0 : caught = caught + 1 else : print (" missed: " , a, b) print (caught, " caught out of 90 " )` **Listing 19.15.** Every swap of two neighbouring digits. code/grade-7/01-functions/listings/swaps.py
13. State the result.

**Solution of Problem 19.1.**

**1.** From the right, the digits 7, 5, 4, 3, 2, 1, 4, 3, 2, 1, 0, 9, 5 are multiplied by 1, 3, 1, 3, …: $7 + 15 + 4 + 9 + 2 + 3 + 4 + 9 + 2 + 3 + 0
+ 27 + 5 = 90$, a multiple of 10.

**2.** With a check digit 0, the weighted sum would be 89. The check digit has weight 1, so it must add 1: the check digit is 1, and the number is `4006381333931`.

**3.** The second digit from the right is 8 instead of 5. Its weight is 3, so the sum grows by $3 \times 3 = 9$: 99, not a multiple of 10. Refused.

**4.** With weight 1, the check digit is simply the amount missing to reach the next multiple of 10. With weight 3, we would have to find a digit whose triple fills the gap.

**5.** When `weight` is 1, `4 - weight` is 3; when it is 3, it is 1. So the weights alternate.

**6.** Multiplying by 10 adds a 0 on the right: a place for the check digit, with weight 1, and every other digit moves to the weight it will have in the full number. If the sum ends in 0, `10 - 0` gives 10, and the second `% 10` turns it into the digit 0.

**7.** `check_digit(400638133393)` returns 1; `is_valid` returns `True` for `5901234123457` and `False` for `5901234123487`.

**8.** Work out the answers by hand first, then print them beside the calls:

- `check_digit(590123412345)` : expected 7 (question 1);
- `check_digit(400638133393)` : expected 1 (question 2);
- `check_digit(100000000003)` : expected 0; the sum is already a multiple of 10 ( $1 + 3 \times 3 = 10$ ), which tests the second `% 10` ;
- `check_digit(100000000000)` : expected 9 (the sum is 1).

**9.** 13 places with 9 other digits each: 117 numbers. All 117 are refused:

```
$ python one_digit.py
117 caught out of 117
```

***Output 19.10.** Every single wrong digit is caught.*

**10.** Changing a digit by $d$ (between $-9$ and 9, not 0) changes the sum by $3 \times d$. For that to be a multiple of 10, $3 \times d$ would have to end in 0; but $3 \times 1, \dots, 3 \times 9$ are 3, 6, 9, 12, 15, 18, 21, 24, 27: none ends in 0. The same holds for negative $d$. With weight 1, the change $d$ itself is between $-9$ and 9 and not 0, so it is not a multiple of 10 either.

**11.** Before: $a \times 1 + b \times 3$; after: $b \times 1 + a \times
3$. The change is $2 \times a - 2 \times b = 2 \times (a - b)$.

**12.** 80 of the 90 swaps are caught:

```
$ python swaps.py
missed: 0 5
missed: 1 6
missed: 2 7
missed: 3 8
missed: 4 9
missed: 5 0
missed: 6 1
missed: 7 2
missed: 8 3
missed: 9 4
80 caught out of 90
```

***Output 19.11.** The 10 missed swaps.*

$2 \times (a - b)$ is a multiple of 10 only when $a - b$ is 5 or $-5$: the missed swaps are exactly the pairs of digits that differ by 5.

**13.** **Result.** Every single wrong digit is caught. Of the 90 swaps of two different neighbouring digits, 80 are caught, and the 10 that are missed are exactly those where the two digits differ by 5.
