A rule for inputs
A function needs two sets. A = {1, 2, 3, 4} holds the inputs; it is called the domain. B = {0, 1, 2} holds the allowed outputs; it is the codomain. We write f: A → B, read 'f maps A to B'.
Our rule is f(x) = x mod 3: divide x by 3 and keep the remainder. Feed in 4: 4 = 1 × 3 + 1, so f(4) = 1. Python writes mod as %. We draw it as an arrow from 4 to 1.
Do the same for every input: f(1) = 1, f(2) = 2 and f(3) = 0. Write each arrow as an ordered pair (input, output), input first. The four pairs are (1, 1), (2, 2), (3, 0) and (4, 1).
Relations and functions
Any set of ordered pairs (a, b), with a from A and b from B, is a relation from A to B. Each pair is one arrow. Order matters: (3, 0) is in our relation, but (0, 3) is not.
A relation is a function when every input has exactly one arrow leaving it: not zero, not two. Here 1, 2, 3 and 4 each have one. Two inputs may share an output: 1 and 4 both go to 1.
Now add the pair (1, 2). The input 1 has two arrows out, so f(1) has no single answer: this relation is not a function. A relation that leaves some input with no arrow is not a function either.
Onto and one-to-one
The range is the set of outputs that are actually hit. {f(x) for x in A} gives {0, 1, 2}, all of B, so f is onto (surjective). The codomain only lists the allowed outputs; a range can be smaller.
f is one-to-one (injective) when different inputs always give different outputs. Ours is not: f(1) = 1 and f(4) = 1. Seeing the output 1, you cannot tell which input made it, so f has no inverse.
In code
A Python dict stores a function as pairs: d = {x: f(x) for x in A} gives {1: 1, 2: 2, 3: 0, 4: 1}. A key can appear only once, so each input keeps exactly one output. d[4] is 1.
Try it in the Python prompt
;; step 1/9 · Inputs and outputs
>>> A = {1, 2, 3, 4}
>>> B = {0, 1, 2}
>>> len(A), len(B)
(4, 3)
>>> 3 in A, 3 in B
(True, False)
f: A → B is read 'f from A to B'. If f(x) = y, then y is the image of x, and x is a preimage of y. The range is the set of all images. Python's % gives a result with the sign of the divisor, so -1 % 3 is 2, which matches maths mod. In C and Java, -1 % 3 is -1.