Instead of writing the same calculation in five places of a program, you can write it once as a function and call it five times. In DİM tasks functions play two roles: either the main character (one function calls another, f(i) stands in a while condition) or a helper that computes a digit, a prime test or a reversed number and is applied to every element of a list. In both cases the key skill is the same: follow which call happens when and which value comes back.
Writing a function: def and return
FunctionDefinition
A named group of commands that runs only when it is called. It is declared with the line def name(parameters):, its body is indented, and the return statement sends the result back to the place of the call.
def square(n):
return n * n
print(square(4))
print(square(3) + square(4))
x = square(square(2))
print(x)Expected output
16 25 16
- The
defline ends with a colon; the body is indented by the same number of spaces. - Python reads the
defblocks and remembers them but does not run them; the program starts at the first unindented line after the functions. returnends the function at once: the lines after it are not executed.- A function without
returnreturnsNone. - A call can stand inside an expression:
square(3) + square(4),square(square(2)).
def f1(n):
print(n * 2)
def f2(n):
return n * 2
print('never')
a = f1(5)
b = f2(5)
print(a, b)Expected output
10 None 10
Formal and actual parameters, local variables
Formal parameterDefinition
The name in the parentheses of the def line: m in def f(m):. At the call it receives the value of the actual parameter.
Actual parameter (argument)Definition
The value or expression written in the parentheses of a call: a + 1 in f(a + 1). Parameters are passed by position: the first actual parameter goes to the first formal parameter, whatever their names are.
Local variableDefinition
A variable created inside a function (formal parameters are local too). It lives only during the call; a variable with the same name in the main program is a different variable, and the function does not change it.
def f(m):
m = m * 2
k = m + 1
return k
m = 5
k = 100
print(f(m), m, k)
def zero_first(a):
a[0] = 0
b = [7, 8, 9]
zero_first(b)
print(b)Expected output
11 5 100 [0, 8, 9]
Inside the function, m and k are local: m becomes 10 and k 11, but m = 5 and k = 100 in the main program stay untouched. A list behaves differently: the function receives the list itself, not a copy, so a[0] = 0 also changes b in the main program. In short: if a number parameter changes inside a function, nothing changes outside; if an element of a list changes, the change is visible outside.
def f(a, b):
a = a - b
return a * 10 + b
a = 3
b = 7
print(f(b, a), a, b)Expected output
43 3 7
DİM-style task (closed)
Problem
Determine the result of the program above.
A) 43 3 7
B) -33 3 7
C) 43 4 3
D) 43 7 3
E) -33 -4 7
Show solutionHide solution
Solution
f(b, a) = f(7, 3): by position the formal a = 7 and the formal b = 3 — equal names change nothing.Inside the function: a = 7 − 3 = 4,
return 4 · 10 + 3 → 43.The main program's
a and b do not depend on the local variables: they stay 3 and 7.Answer: A. B is the mistake of passing parameters by name, C of thinking that local variables “leak” outside.
One function calls another: the order of calls
Find the start
Skip the
defblocks and start at the first line of the main program.Write the parameters
At every call copy the actual values into the formal parameters by position; one row of a table: function, parameters, local variables.
Inside out
If there is another call inside the function, pause the current one, finish the inner call and continue with the value it returns. In
f(g(x)),g(x)is computed first.Go back
After
return, go back to the place of the call and replace the call by the returned value.Count
Note how many times each function is called — a missed call is the most common mistake.
def g(x):
return x % 10 + x // 10
def f(n):
p = g(n) * 3
q = g(p) + g(n + 5)
return p + q
print(f(47))Expected output
46
| Call | Returns | Inside f |
|---|---|---|
g(47) = 7 + 4 | 11 | p = 11 · 3 = 33 |
g(33) = 3 + 3 | 6 | g(n + 5) is still waiting |
g(52) = 2 + 5 | 7 | q = 6 + 7 = 13 |
f(47) | 46 | return 33 + 13 |
g is called three times, f once; n + 5 = 52 is computed before it is passed to the function.def g(k):
k = k + 3
return k * 2
def f(m):
m = g(m) - m
n = g(m) + m
return n
a = 4
print(f(a) + a)Expected output
40
DİM-style task (closed)
Problem
Determine the result of the program above.
A) 36 B) 40 C) 22 D) 34 E) 52
Show solutionHide solution
Solution
f(4) is called.g(4): k = 7, returns 14 → m = 14 − 4 = 10 (the local m changed).g(10): k = 13, returns 26 → n = 26 + 10 = 36.f(4) = 36, the program prints 36 + 4 = 40 (B).Wrong paths: A — forgetting the final
+ a; C — ignoring the new value of m: 14 + 4 + 4 = 22; D — taking the old m = 4 in the second line: 26 + 4 + 4 = 34; E — forgetting - m in the first line.Helper functions: over lists and in loop conditions
The most common helper functions in DİM programs are small algorithms: returning a digit (n // 10 % 10 is the tens digit), a prime test by counting divisors, reversing a number, the digit sum. They work in three places: on every element of a list as in a[i] = k(a[i]), as a filter as in if f(x) != 0: b.append(x), and in a loop condition as in while f(i) < g(k):. The digit algorithms themselves are explained in the lesson “Working with numbers: digits, divisors and primes”; here we “pack” them into functions.
def d(n):
k = 0
for i in range(1, n + 1):
if n % i == 0:
k = k + 1
return k
a = [9, 11, 15, 2, 21, 29, 1]
for i in range(0, len(a)):
if d(a[i]) != 2:
a[i] = d(a[i])
print(a)Expected output
[3, 11, 4, 2, 4, 29, 1]
d(n) returns the number of divisors. Primes have exactly two divisors (1 and themselves), so 11, 2, 29 stay, while 9, 15, 21 are replaced by their numbers of divisors — 3, 4, 4. The number 1 has only one divisor: 1 is not a prime, and since d(1) = 1 the element stays 1.
def rev(n):
r = 0
while n > 0:
r = r * 10 + n % 10
n = n // 10
return r
def tens(n):
return n // 10 % 10
for x in [123, 450, 707, 81]:
print(x, rev(x), tens(x), x == rev(x))Expected output
123 321 2 False 450 54 5 False 707 707 0 True 81 18 8 False
DİM-style task (coded answer)
Problem
Determine the number printed by the program.def t(n): return n // 10 % 10def e(n): return n % 10a = [352, 417, 626, 95, 1203]b = []for x in a: b.append(t(x) * e(x))print(sum(b) + len(b))
Show solutionHide solution
Solution
t(n) returns the tens digit, e(n) the units digit. The product for every element:352 → 5 · 2 = 10
417 → 1 · 7 = 7
626 → 2 · 6 = 12
95 → 9 · 5 = 45 (in a two-digit number the tens digit is the first digit)
1203 → 0 · 3 = 0 (the tens digit is 0)
b = [10, 7, 12, 45, 0], sum 74,
len(b) = 5.Answer: 74 + 5 = 79.
DİM-style task (closed)
Problem
If −20 is entered from the keyboard, determine the result of the program.def f(n): return n * n + 1def g(n): return 3 * n - 4k = abs(int(input()))i = 0while f(i) <= g(k): i = i + 2print(i)
A) 6 B) 7 C) 8 D) 10 E) 4
Show solutionHide solution
Solution
i = 0: f(0) = 1 ≤ 56 → i = 2
i = 2: f(2) = 5 ≤ 56 → i = 4
i = 4: f(4) = 17 ≤ 56 → i = 6
i = 6: f(6) = 37 ≤ 56 → i = 8
i = 8: f(8) = 65 > 56 → the loop ends
Answer: C) 8. A is the last value for which the condition held, but
i is increased after that.| Function | What it returns | Example |
|---|---|---|
abs(x) | the absolute value | abs(-7) → 7 |
len(s) | the number of characters in a string or elements in a list | len('python') → 6 |
min(...), max(...) | the smallest / largest of several numbers or of a list | min(4, 9, 2) → 2, max([3, 8, 5]) → 8 |
str(n) | turns a number into a string | len(str(305)) → 3 |
int(x) | turns a string into a number; drops the fractional part | int('42') → 42, int(7.9) → 7 |
list(s) | makes a list of characters from a string | list('abc') → ['a', 'b', 'c'] |
sum(a) | the sum of the elements of a list | sum([2, 5, 1]) → 8 |
Exercise
Write the function digit_sum(n) that returns the sum of the digits of a natural number n. Then print, each on its own line, the numbers of the list a whose digit sum is divisible by 3, and finally print how many there are.
def digit_sum(n):
s = 0
# add the digits of n to s
return s
a = [12, 45, 71, 303, 58, 999]Expected output
12 45 303 999 4
Exercise
Let the function is_prime(n) count the divisors of n and return True when there are exactly 2. Print the number of primes in the list a, then the largest prime.
def is_prime(n):
k = 0
# count the divisors of n
return k == 2
a = [15, 7, 22, 13, 1, 9, 31, 4]Expected output
3 31
This completes the module's “toolbox”: variables, conditions, loops, strings, lists and functions. In the next lesson, “Writing programs: the written tasks”, we combine them and write the exam's written tasks as complete programs. Reverse tasks of the while f(i) … type, where you find the input from the output, are in the lesson “Analysing programs: from the output back to the input”, and extras such as default parameters are in the Python course lesson “Functions”.
Remember
- A function is declared with
defand runs only when called;returnsends the result back, without it you getNone. - Actual parameters go to the formal ones by position, not by name.
- Local variables vanish after the call; changing a number parameter does not affect the outside, changing a list element does.
- Nested calls are evaluated from the inside out; write each call's returned value above it.
- In a
while f(i) < g(k)loop compute the right side once, then follow the values off(i)in a table.