Kids Coding
Functions
A function is a named recipe. Write it once. Call it whenever you need it.
KidsIntermediateFunctions
A named recipe
A function is a chunk of code with a name. You write it once with def. You run it by calling the name with ().
Say hello
def hello():
print("Hello")
print("Welcome")
hello()
hello()Name a function for what it does: say_hello, not thing. Future-you will thank present-you when you read the code next week.
Pass something in
The name in the brackets is a parameter: a box that only exists inside the function.
hello(name)
def hello(name):
print("Hello, " + name)
hello("Sam")
hello("Riley")Why bother
- You do not copy-paste the same three lines.
- If you fix the function, every call is fixed.
- The rest of the program reads like a list of steps.
Real life
Making the same sandwich every day.
You do not rewrite the recipe. You follow it. def is the recipe. Calling it is lunchtime.
Sandwich recipe
def sandwich(filling):
print("Bread")
print(filling)
print("Bread")
print("---")
sandwich("cheese")
sandwich("jam")Change one word. Run it. That is how this idea shows up outside the lesson.
Try it
Exercise 1: Write cheer(team) that prints Go and the team name. Call it twice.
Show solution
def cheer(team):
print("Go " + team)
cheer("Foxes")
cheer("Owls")