Naming and reusing pieces of code
October 2, 2026
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.
Define with def, a name, parentheses, and a colon; the body is indented:
Nothing happens until you call it — and the call must come after the definition:
This is a function
That's all it does
------------------------------
SHOPPING LIST
------------------------------
apples
bread
------------------------------
Three separators, written once.
And when the style has to change, you change that one line, and all three separators follow:
==============================
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.
Recall Lecture 2: names created inside a function live only there.
This is your word: grammar
…and gone as soon as the call ends. Outside, the name means nothing:
--------------------------------------------------------------------------- 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
A function can read names from the enclosing (global) scope:
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.
A local name belongs to the one function that creates it:
funcA sees: 42
funcB writes the same name — but nothing ever created it in its room:
--------------------------------------------------------------------------- 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
What happens to the outer size when the function assigns to size?
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.)
return keywordreturn hands a value back to the caller and ends the function:
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.
return go back to?A call pauses the caller. When the function returns, the machine resumes at the exact point it left:
outer starts
middle starts
inner runs
middle resumes: inner done
outer resumes: middle done
The machine keeps a stack of the calls still waiting:
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 let a function work on different inputs:
13
strings too
The same + works on numbers and strings — the function doesn’t care, as long as + makes sense for the values.
NoneIf a path doesn’t return, the function returns None:
The word is too short!
None
A function can return multiple values (as a tuple), unpacked at the call site:
5 5 hello world
The name in the def — the parameter — is local to the function; the value in the call is the argument:
a value
another value!
a value
Reassigning a inside did not touch x outside.
If you pass a list or dict and mutate it, the caller sees the change:
[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.
Arguments can be given by position or by name:
one way
another way
yet way
Defaults make an argument optional:
hat oops
hat chair
*args collects extra positional arguments; **kwargs collects named ones:
3
6
8
hat -> wow
chair -> 3.5
Useful when you don’t know in advance how many inputs there will be.
You can pass a function as an argument, or return one:
3
5
This is higher-order programming — powerful, but use it sparingly at first.
Some problems are naturally defined in terms of themselves. A recursive function needs a base case (to stop) and a recursive case.
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?”
A lambda is a one-line function with no name, handy for short throwaway logic:
25
Most useful as an argument to functions like sorted:
['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.
return gives a value back; print only displays.print or return?Two functions, one word apart. Predict what the four lines print.
HI
None
HI
HI appears while shout_print runs — but it hands nothing back, so a is None. shout_return prints nothing at all; it gives back "HI", which is why print(b) can show it.
Screen output and returned value are two different things. A function that only prints is a dead end: you cannot use its result for anything.
Both functions modify their argument. Predict what is left outside.
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.
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.
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.
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)
letter — a single character, such as "d"ALPHABET, counting from 0 — or -1 if it is not one of the 26 lettersHint: walk through ALPHABET with a for, keep a counter, and return the moment you find it.
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.
Write shift_letter(letter, n)
letter — a single character; and n — a whole number, the keyn 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.
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.
One letter at a time is not a cipher yet.
Write encrypt(message, n)
message — a string of any length; and n — the keynLower 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.
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.
Write decrypt(message, n)
message — an encrypted string; and n — the key it was encrypted withdecrypt(encrypt(t, n), n) must give back tStop and think before writing. How much new code does this really need?
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.
Someone sends you this, and you do not know the key:
But a Caesar cipher has only 26 possible keys, so try them all.
Write crack(message)
message — an encrypted string whose key is unknown0 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.
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).
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:
''
'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.
fac_loop(n) using a for loop.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?
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.
Write word_count(sentence) returning the number of words in a sentence:
Stretch: write word_frequency(sentence) returning a dict of word -> count, then most_frequent_word(sentence) that reuses it.
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.
Write initials(full_name) that turns a name into its initials, one capital letter and a dot each:
It must work for any number of names, and lower-case input must still come out capitalised.
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.
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.
Write two functions that add a suffix to every word in a list:
add_suffix_inplace(words, suffix) — changes the caller’s list, returns nothing;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 untoucheda: ['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.
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:
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.
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.
Intro to Programming (Python) · Fall 2026