Unit 8: Smarter Functions
Defaults, scope and recursion.
Unit 8 of 31 in Python for kids. Its 5 lessons are Ready-Made Answers, More Than One Answer, Where Names Live, Functions That Call Themselves and Function Workshop — below is everything each one explains, and a question or two from it to try.
Every sample on this page was run through real Python before it shipped, and prints exactly what it says it prints.
This unit opens with a fortnight’s trial of everything — no card needed — or with a family plan, bought in the iPhone app. The first two units of every track are free for ever. Try it in the app.
🎁 Ready-Made Answers
An argument that fills itself in
Give a parameter a value in the def line and it becomes optional. Leave it out when you call, and the ready-made value is used.
Python
def greet(name, greeting="Hello"):
print(greeting + " " + name)
greet("Ada")
greet("Sam", "Howdy")
It prints
Hello Ada Howdy Sam
Naming the argument
You can also say which parameter you mean by name. Handy when a function has several optional ones and you only want to change the last.
Python
def draw(shape="star", size=1):
print(shape * size)
draw(size=3)
It prints
starstarstar
Try it yourself
What does this print?
Python
def shout(word, times=2):
print(word * times)
shout("hi")
shout("hi", 3)
Where must parameters with a default go?
- First, before the ordinary ones
- Last, after the ordinary ones
- Anywhere
- On their own line
Answer them in the app
🎒 More Than One Answer
Returning two things at once
Separate values with a comma after return and the function hands back all of them. Catch them with matching names on the left.
Python
def best_and_worst(scores):
return max(scores), min(scores)
high, low = best_and_worst([4, 9, 2])
print(high)
print(low)
It prints
9 2
That bundle is a tuple
A tuple is a little list that can never be changed. Round brackets instead of square ones — and Python makes one for you whenever you write values with commas.
Python
point = (3, 7)
print(point)
print(point[0])
It prints
(3, 7) 3
Try it yourself
What is the difference between a tuple and a list?
- A tuple holds only numbers
- A tuple cannot be changed once it is made
- A tuple is faster to print
- There is no difference
What does this print?
Python
def split_name(full):
return full[0], full[-1]
first, last = split_name("Ada")
print(first + last)
Answer them in the app
🏠 Where Names Live
A function has its own little world
A name created inside a function only exists inside it. When the function ends, the name is gone — which is why two functions can both use n without ever getting confused.
Python
def add():
total = 5
print(total)
add()
print("done")
It prints
5 done
Looking outwards is fine
A function can *read* a name from outside. It just cannot change one by ordinary assignment — that would quietly make a new local name instead.
Python
score = 10
def show():
print(score)
show()
It prints
10
Better than global: return it
Python has a global keyword, but reaching out and changing outside names makes programs hard to follow. Returning the new value is nearly always tidier.
Python
score = 10
def bump(current):
return current + 1
score = bump(score)
print(score)
It prints
11
Try it yourself
What happens if you print(total) *after* that function, outside it?
- It prints 5
- It prints 0
- Python complains that total is not defined
- It prints nothing
Careful — what does this print?
Python
score = 10
def bump():
score = 99
bump()
print(score)
Answer them in the app
🪆 Functions That Call Themselves
Russian dolls
A function is allowed to call itself. That is called recursion, and it needs two parts: a way to stop, and a step that gets closer to stopping.
Python
def countdown(n):
if n == 0:
print("Liftoff!")
return
print(n)
countdown(n - 1)
countdown(3)
It prints
3 2 1 Liftoff!
Building an answer on the way back
Each call waits for the one inside it to finish, then uses that answer. factorial(4) is 4 times whatever factorial(3) works out to be.
Python
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
print(factorial(4))
It prints
24
Try it yourself
What is the stopping part called?
- The end case
- The base case
- The stop case
- The final case
What does this print?
Python
def total(n):
if n == 0:
return 0
return n + total(n - 1)
print(total(4))
Answer them in the app
🏆 Function Workshop
Try it yourself
What does this print?
Python
def tag(word, mark="!"):
return word + mark
print(tag("hi"))
print(tag("hi", "?"))
Answer it in the app