Functions

Naming and reusing pieces of code

Paolo Rota

October 2, 2026

Why functions?

As programs grow they get repetitive and hard to follow. Repetition is error-prone: fix a bug in one copy, forget the other four.

A function packages a piece of code under a name, so you can reuse it, read it, and fix it in one place. Functions are the first big tool for taming complexity.

Defining & calling

A simple function

Define with def, a name, parentheses, and a colon; the body is indented:

def myfunction():
    print("This is a function")
    print("That's all it does")

Nothing happens until you call it — and the call must come after the definition:

myfunction()      # invoke it
This is a function
That's all it does

Functions remove repetition

def line():
    print("-" * 30)

def report():
    line()
    print("SHOPPING LIST")
    line()
    print("apples")
    print("bread")
    line()

report()
------------------------------
SHOPPING LIST
------------------------------
apples
bread
------------------------------

Three separators, written once.

Functions remove repetition

And when the style has to change, you change that one line, and all three separators follow:

def line():
    print("=" * 30)      # the only thing we edited

report()                 # every separator follows
==============================
SHOPPING LIST
==============================
apples
bread
==============================

report did not change at all, yet its output did: it asks line to do that job, and line now does it differently. That is the whole argument for functions — one place to fix.

Scope, revisited

Local variables

Recall Lecture 2: names created inside a function live only there.

def myfunc():
    word = "grammar"           # born here...
    print("This is your word:", word)

myfunc()
This is your word: grammar

…and gone as soon as the call ends. Outside, the name means nothing:

print(len(word))       # NameError: 'word' was local to myfunc
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[6], line 1
----> 1 print(len(word))       # NameError: 'word' was local to myfunc

NameError: name 'word' is not defined

Reading outer variables

A function can read names from the enclosing (global) scope:

word = "grammar"           # defined OUTSIDE, at the top level

def myfunc():
    print("This is your word:", word)   # reads the global 'word'

myfunc()
This is your word: grammar

Relying on globals inside functions is usually a bad idea — it makes functions depend on hidden state: the same call gives different answers depending on what happened elsewhere. The cure is to pass the values in, as arguments — we get there right after return.

Two functions, two rooms

A local name belongs to the one function that creates it:

def funcA():
    secret = 42                    # born inside funcA
    print("funcA sees:", secret)

def funcB():
    print("funcB sees:", secret)   # is 'secret' visible in here?

funcA()
funcA sees: 42

funcB writes the same name — but nothing ever created it in its room:

funcB()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[9], line 1
----> 1 funcB()

Cell In[8], line 6, in funcB()
      5 def funcB():
----> 6     print("funcB sees:", secret)   # is 'secret' visible in here?

NameError: name 'secret' is not defined

The same name in two places

What happens to the outer size when the function assigns to size?

size = 10                  # global name

def resize():
    size = 99              # assignment: creates a NEW, local 'size'
    print("inside: ", size)

resize()
print("outside:", size)    # did the call change it?
inside:  99
outside: 10

Reading a name the function doesn’t own falls back to the outer scope. Assigning always creates or updates a local one. So a function cannot re-point a global name by accident. (Changing a shared list is another story — a few slides on.)

Returning values

The return keyword

return hands a value back to the caller and ends the function:

def myfunc():
    print("This prints.")
    return 6
    print("This does NOT print.")   # unreachable

x = myfunc()
print("output:", x)
This prints.
output: 6

print shows a value on screen; return gives a value back to the code that called the function. They are not the same thing.

Where does return go back to?

A call pauses the caller. When the function returns, the machine resumes at the exact point it left:

def inner():
    print("    inner runs")
    return "inner done"

def middle():
    print("  middle starts")
    r = inner()                      # middle waits here
    print("  middle resumes:", r)
    return "middle done"

def outer():
    print("outer starts")
    r = middle()                     # outer waits here
    print("outer resumes:", r)

outer()
outer starts
  middle starts
    inner runs
  middle resumes: inner done
outer resumes: middle done

The call stack

The machine keeps a stack of the calls still waiting:

outer

outer middle

outer middle inner

outer middle

outer outer() called calls middle() calls inner() inner returns middle returns the stack grows ▸ ◂ and unwinds

Only the top box on the stack — the call running now — is active; everything under it is waiting for a return. This is also why an error prints several lines: the traceback is the whole stack, most recent call last.

Arguments

Passing data in

Arguments let a function work on different inputs:

def add(a, b):
    return a + b

print(add(3, 10))
print(add("strings ", "too"))
13
strings too

The same + works on numbers and strings — the function doesn’t care, as long as + makes sense for the values.

Missing returns give None

If a path doesn’t return, the function returns None:

def sillyfunc(wd):
    if len(wd) > 4:
        return len(wd)
    else:
        print("The word is too short!")

res = sillyfunc("hi")     # prints the warning...
print(res)                # ...and res is None
The word is too short!
None

Returning several values

A function can return multiple values (as a tuple), unpacked at the call site:

def stats(x, y):
    z = x + " " + y
    return len(x), len(y), z

a, b, c = stats("hello", "world")
print(a, b, c)
5 5 hello world

Arguments are the safe alternative to globals

The name in the def — the parameter — is local to the function; the value in the call is the argument:

x = "a value"

def anotherfunc(a):
    a = "another value!"
    return a

print(x)
print(anotherfunc(x))
print(x)                 # unchanged
a value
another value!
a value

Reassigning a inside did not touch x outside.

But mutable arguments can be changed!

If you pass a list or dict and mutate it, the caller sees the change:

x = [4, 5, 6]

def addseven(a):
    a.append(7)          # mutates the SAME list
    return a

print(addseven(x))
print(x)                 # changed!
[4, 5, 6, 7]
[4, 5, 6, 7]

Reassigning a parameter is local; mutating a shared mutable object is visible everywhere. Remember the reference trap from Lecture 3.

Keyword & default arguments

Arguments can be given by position or by name:

def glue(x, y):
    return x + " " + y

print(glue("one", "way"))            # positional
print(glue(x="another", y="way"))    # by keyword
print(glue(y="way", x="yet"))        # order-free with keywords
one way
another way
yet way

Defaults make an argument optional:

def f(x, y="oops"):
    return x + " " + y

print(f("hat"))            # y falls back to the default
print(f("hat", "chair"))   # y is given
hat oops
hat chair

Any number of arguments

*args collects extra positional arguments; **kwargs collects named ones:

def func(*args, **kwargs):
    for a in args:
        print(a)
    for k in kwargs:
        print(k, "->", kwargs[k])

func(3, 6, 8, hat="wow", chair=3.5)
3
6
8
hat -> wow
chair -> 3.5

Useful when you don’t know in advance how many inputs there will be.

A little more

Functions are values too

You can pass a function as an argument, or return one:

def apply(f, x):
    return f(x)

print(apply(len, "hat"))    # 3

def picker(letter):
    if letter == "L":
        return len          # the function itself, not a call
    else:
        return type

print(picker("L")("chair"))  # 5
3
5

This is higher-order programming — powerful, but use it sparingly at first.

Recursion — a function that calls itself

Some problems are naturally defined in terms of themselves. A recursive function needs a base case (to stop) and a recursive case.

def fac(n):
    if n <= 1:          # base case
        return 1
    else:               # recursive case
        return n * fac(n - 1)

print(fac(5))
print(fac(0), fac(1))   # the base case covers both
120
1 1

Trace fac(3): 3 * fac(2) → 3 * (2 * fac(1)) → 3 * 2 * 1 = 6.

Why n <= 1 and not n == 1? Because fac(0) would then never reach the base case: it would call fac(-1), fac(-2), … for ever. Without a reachable base case, recursion is an infinite loop that eventually crashes with a RecursionError. Always ask: “what makes it stop, for every input?”

Lambda — tiny anonymous functions

A lambda is a one-line function with no name, handy for short throwaway logic:

square = lambda n: n * n
print(square(5))
25

Most useful as an argument to functions like sorted:

words = ["pear", "fig", "banana"]
print(sorted(words, key=lambda w: len(w)))
['fig', 'pear', 'banana']

key= tells sorted what to sort by: here, each word’s length.

For anything longer than one expression, use a normal def.

What to take away

  1. Functions name and reuse code; fix bugs in one place.
  2. return gives a value back; print only displays.
  3. Prefer arguments over globals; beware mutating shared objects.
  4. Recursion needs a base case; lambdas are tiny one-expression functions.

Try it now

Does it change?

Both functions modify their argument. Predict what is left outside.

def add_one(n):
    n = n + 1
    return n

def add_item(lst):
    lst.append("new")
    return lst

number = 10
things = ["a"]

add_one(number)
add_item(things)

print(number, things)
10 ['a', 'new']

10 ['a', 'new']. add_one rebinds its own local name n — the caller’s number never moves. add_item mutates the very list it was handed, and that list is the one things points to.

Same code shape, opposite outcome: it depends on whether the value is mutable, and on whether you reassign or mutate. Lecture 3 again.

The Caesar cipher

A message nobody else can read

Every letter slides forward by the same number of places. With a shift of 3, a becomes d, b becomes e, and so on. That number is the key: whoever knows it can read the message.

ALPHABET = "abcdefghijklmnopqrstuvwxyz"

print(ALPHABET)
print("a becomes", ALPHABET[0 + 3])    # 'a' is at 0, shift 3 -> position 3
abcdefghijklmnopqrstuvwxyz
a becomes d

We build it in five steps, one small function each. By the last one we will read a message whose key we do not know.

Step 1 — Where is this letter?

ALPHABET[3] gives you "d". Now you need the opposite question: given the letter "d", which position is it at? Python has a tool for this, but we have not met it — so write it yourself.

Write position(letter)

  • takes letter — a single character, such as "d"
  • returns an integer: where that character sits inside ALPHABET, counting from 0 — or -1 if it is not one of the 26 letters
position("a")   # -> 0
position("z")   # -> 25
position("!")   # -> -1

Hint: walk through ALPHABET with a for, keep a counter, and return the moment you find it.

def position(letter):
    i = 0
    for ch in ALPHABET:
        if ch == letter:
            return i          # found: leave at once
        i = i + 1
    return -1                 # the loop ended: never found

print(position("a"), position("z"), position("!"))
0 25 -1

return inside the loop ends the whole function, loop included. So the last line is reached only when nothing matched — that is what -1 means.

Step 2 — Move it along

Write shift_letter(letter, n)

  • takes letter — a single character; and n — a whole number, the key
  • returns a single character: the letter n places further along the alphabet. Anything not in ALPHABET — spaces, punctuation, capitals — comes back unchanged (not in is the opposite question of in)

Two things to get right: what happens past z, and what happens to a space.

a b c d efg hij klm nop qrs tuv wxy z a + 3 z + 3 runs past the end — so it starts again from the front
shift_letter("a", 3)   # -> 'd'      shift_letter("z", 3)   # -> 'c'
shift_letter(" ", 3)   # -> ' '      (not a letter: leave it alone)
def shift_letter(letter, n):
    if letter not in ALPHABET:
        return letter                        # spaces, commas... pass through
    return ALPHABET[(position(letter) + n) % 26]

print(shift_letter("a", 3), shift_letter("z", 3), "[" + shift_letter(" ", 3) + "]")
d c [ ]

25 + 3 is 28, and 28 % 26 is 2 — position 2 is c. The % is what bends the alphabet into a ring. Without it, z would raise an IndexError.

Step 3 — A whole message

One letter at a time is not a cipher yet.

Write encrypt(message, n)

  • takes message — a string of any length; and n — the key
  • returns a new string of the same length, with every character shifted by n
encrypt("Meet me at noon!", 3)   # -> 'phhw ph dw qrrq!'

Lower the message first with .lower(), so that M and m behave the same. Then build the answer one character at a time, calling the function you wrote in step 2 — do not touch ALPHABET again here.

Hint: start from an empty string and keep adding to it.

def encrypt(message, n):
    result = ""
    for ch in message.lower():
        result = result + shift_letter(ch, n)
    return result

coded = encrypt("Meet me at noon!", 3)
print(coded)
phhw ph dw qrrq!

Notice the spaces and the ! survived untouched: that is the guard you wrote in step 2 paying off now. encrypt never looks at what a character is — it asks shift_letter, and trusts the answer.

Step 4 — And back again

Write decrypt(message, n)

  • takes message — an encrypted string; and n — the key it was encrypted with
  • returns a new string: the original message. decrypt(encrypt(t, n), n) must give back t

Stop and think before writing. How much new code does this really need?

def decrypt(message, n):
    return encrypt(message, -n)

print(decrypt(coded, 3))
meet me at noon!

One line. Shifting back by n is shifting forward by -n, and the % handles the negative just as well: 0 - 3 is -3, and -3 % 26 is 23 — position 23 is x, exactly where a came from.

The function you needed was already written. This is the whole point of functions: the second use costs one line.

Step 5 — Break it without the key

Someone sends you this, and you do not know the key:

"wkh vhfuhw lv vdih"

But a Caesar cipher has only 26 possible keys, so try them all.

Write crack(message)

  • takes message — an encrypted string whose key is unknown
  • returns nothing — it prints 26 lines, the key and what the message would say with it. Your eyes do the last step
def crack(message):
    for n in range(26):
        print(n, decrypt(message, n))

crack("wkh vhfuhw lv vdih")
0 wkh vhfuhw lv vdih
1 vjg ugetgv ku uchg
2 uif tfdsfu jt tbgf
3 the secret is safe
4 sgd rdbqds hr rzed
5 rfc qcapcr gq qydc
6 qeb pbzobq fp pxcb
7 pda oaynap eo owba
8 ocz nzxmzo dn nvaz
9 nby mywlyn cm muzy
10 max lxvkxm bl ltyx
11 lzw kwujwl ak ksxw
12 kyv jvtivk zj jrwv
13 jxu iushuj yi iqvu
14 iwt htrgti xh hput
15 hvs gsqfsh wg gots
16 gur frperg vf fnsr
17 ftq eqodqf ue emrq
18 esp dpncpe td dlqp
19 dro combod sc ckpo
20 cqn bnlanc rb bjon
21 bpm amkzmb qa ainm
22 aol zljyla pz zhml
23 znk ykixkz oy yglk
24 ymj xjhwjy nx xfkj
25 xli wigvix mw weji

Key 3. Twenty-six lines of nonsense and one sentence — and your eye finds it instantly, which a program would find much harder. Five small functions, and you have broken the cipher Julius Caesar himself used.

Take home

Exercise 1 — Absolute difference

Write a function diff(a, b) that returns a - b if a > b, and b - a otherwise — without using the built-in abs. Test it with diff(9, 4), diff(4, 9), diff(5, 5).

def diff(a, b):
    if a > b:
        return a - b
    else:
        return b - a

print(diff(9, 4), diff(4, 9), diff(5, 5))
5 5 0

Both branches return, so there is no path that falls off the end and yields None. diff(5, 5) takes the else and returns 0 — correct either way.

Exercise 2 — Concatenate any number of strings

Write concat(*args) that joins any number of strings with a single space between them, and returns the result. It must handle the edge cases:

concat()                              # -> ""
concat("ciao")                        # -> "ciao"
concat("ciao", "hello", "hola")       # -> "ciao hello hola"
def concat(*args):
    return " ".join(args)

print(repr(concat()))
print(repr(concat("ciao")))
print(repr(concat("ciao", "hello", "hola")))
''
'ciao'
'ciao hello hola'

" ".join(...) from Lecture 3 already handles both edge cases: nothing to join gives "", one item gives that item with no separator added. repr is used here only so the empty string is visible.

Exercise 3 — Factorial, two ways

  1. Write fac_loop(n) using a for loop.
  2. Write fac_rec(n) using recursion (with a base case).

Check they agree for n = 0, 1, 5, 10. What should fac(0) be, and does your base case handle it?

def fac_loop(n):
    result = 1
    for i in range(2, n + 1):     # empty range when n is 0 or 1
        result = result * i
    return result

def fac_rec(n):
    if n <= 1:                    # base case: covers 0 AND 1
        return 1
    else:
        return n * fac_rec(n - 1)

for n in [0, 1, 5, 10]:
    print(n, fac_loop(n), fac_rec(n))
0 1 1
1 1 1
5 120 120
10 3628800 3628800

0! is 1 by definition. The loop version gets it for free — range(2, 1) is empty, so result stays 1. The recursive one needs n <= 1: with n == 1 it would call fac_rec(-1), fac_rec(-2), … and crash.

Exercise 4 — Word count

Write word_count(sentence) returning the number of words in a sentence:

word_count("The quick brown fox jumps over the lazy dog")   # -> 9

Stretch: write word_frequency(sentence) returning a dict of word -> count, then most_frequent_word(sentence) that reuses it.

def word_count(sentence):
    return len(sentence.split())

print(word_count("The quick brown fox jumps over the lazy dog"))
9
def word_frequency(sentence):
    freq = {}
    for w in sentence.split():
        freq[w] = freq.get(w, 0) + 1     # .get with a default, Lecture 3
    return freq

def most_frequent_word(sentence):
    freq = word_frequency(sentence)      # reuse, do not repeat
    best = ""
    best_count = 0
    for word in freq:
        if freq[word] > best_count:
            best = word
            best_count = freq[word]
    return best

s = "the cat sat on the mat the end"
print(word_frequency(s))
print(most_frequent_word(s))
{'the': 3, 'cat': 1, 'sat': 1, 'on': 1, 'mat': 1, 'end': 1}
the

The point of the stretch is the first line of most_frequent_word: it calls word_frequency instead of counting again. Small functions that call each other beat one long one.

Exercise 5 — Initials

Write initials(full_name) that turns a name into its initials, one capital letter and a dot each:

initials("paolo rota")             # -> "P.R."
initials("Gabriel Garcia Marquez") # -> "G.G.M."

It must work for any number of names, and lower-case input must still come out capitalised.

def initials(full_name):
    result = ""
    for part in full_name.split():      # split gives one item per name
        result = result + part[0].upper() + "."
    return result

print(initials("paolo rota"))
print(initials("Ada Lovelace"))
print(initials("Gabriel Garcia Marquez"))
P.R.
A.L.
G.G.M.

split() is what makes “any number of names” free: the loop does not care how many items it gets. part[0] is the first character — indexing from Lecture 3.

Exercise 6 — The longest word

Write longest(words) returning the longest string in a list. Then give it a default argument min_length=0, so that longest(words, min_length=10) only considers words of at least that length.

What should it return when nothing qualifies? Decide, and make it happen on purpose.

def longest(words, min_length=0):
    best = ""
    for w in words:
        if len(w) >= min_length and len(w) > len(best):
            best = w
    return best

fruit = ["fig", "banana", "kiwi", "pear"]
print(repr(longest(fruit)))
print(repr(longest(fruit, min_length=10)))   # nothing qualifies
print(repr(longest([])))                     # nothing at all
'banana'
''
''

Starting best at "" answers both edge cases for free: an empty string is what comes back when no word qualifies, and len("") is 0, so the first real word always wins.

Exercise 7 — Change it, or copy it

Write two functions that add a suffix to every word in a list:

  1. add_suffix_inplace(words, suffix) — changes the caller’s list, returns nothing;
  2. add_suffix_copy(words, suffix) — leaves the original alone and returns a new list.

Then call both on identical lists and print what is left outside.

def add_suffix_inplace(words, suffix):
    for i in range(len(words)):
        words[i] = words[i] + suffix    # writing into the caller's list

def add_suffix_copy(words, suffix):
    result = []
    for w in words:
        result.append(w + suffix)       # building a list of our own
    return result

a = ["cat", "dog"]
b = ["cat", "dog"]

add_suffix_inplace(a, "s")
new = add_suffix_copy(b, "s")

print("a:", a)                  # changed
print("b:", b, " new:", new)    # b untouched
a: ['cats', 'dogs']
b: ['cat', 'dog']  new: ['cats', 'dogs']

Two honest designs, and the difference is visible from outside. The copying one is usually the safer default: nobody is surprised by it.

Exercise 8 — A vowel report

Write count_vowels(word) returning how many vowels a word has. Then write vowel_report(words) that uses it to build a dictionary word -> vowel count:

vowel_report(["sky", "banana", "Europe"])
# -> {'sky': 0, 'banana': 3, 'Europe': 4}

The second function must call the first to do the counting.

def count_vowels(word):
    n = 0
    for ch in word.lower():        # lower() so A counts as a vowel too
        if ch in "aeiou":
            n += 1
    return n

def vowel_report(words):
    report = {}
    for w in words:
        report[w] = count_vowels(w)    # reuse, do not repeat
    return report

print(count_vowels("Appalachicola"))
print(vowel_report(["sky", "banana", "Europe"]))
6
{'sky': 0, 'banana': 3, 'Europe': 4}

Each function does one job: counting, and collecting. That is why count_vowels is testable on its own, and why vowel_report is three lines.

Exercise 9 — Palindromes, recursively

A word is a palindrome if it reads the same backwards: radar, anna.

Write is_palindrome(word) recursively. Ignore capitals. Think about the base case first: which words are obviously palindromes without checking anything?

def is_palindrome(word):
    word = word.lower()

    if len(word) <= 1:              # base case: 0 or 1 letters
        return True
    if word[0] != word[-1]:         # ends differ -> done, it is not
        return False

    return is_palindrome(word[1:-1])   # strip both ends, ask again

for w in ["radar", "Anna", "python", "a", ""]:
    print(repr(w), is_palindrome(w))
'radar' True
'Anna' True
'python' False
'a' True
'' True

One base case plus an early exit, and both are needed: <= 1 stops the recursion, and the mismatch check stops it early — no point stripping further once you know the answer. Each call works on a shorter word, so the base case is always reached.

Questions?