Think about teaching a dog to "sit." You do not explain every muscle movement each time. You say one word, and the dog knows the whole trick. A function is the same idea for code: you give a group of instructions a name, then use the name whenever you want those instructions to run.
Your first function
def say_hello():
print("Hello!")
print("Welcome to my program.")
say_hello()
say_hello()Let us read it piece by piece:
defmeans "I am defining a new function."say_hellois the name we chose.- The brackets
()and the colon:are required. - The indented lines are the body, the instructions that belong to the function.
Defining a function does not run it. It is like writing a recipe. The recipe only gets cooked when you call it by writing say_hello(). Here we call it twice, so the message prints twice.
Giving a function something to work with
Functions get more useful when you can hand them information. These pieces of information are called parameters.
def greet(name):
print("Hello,", name)
greet("Maya")
greet("Leo")The same function now greets different people. Inside the function, name acts like a variable that holds whatever you passed in.
Getting an answer back
Some functions calculate something and give the result back using return:
def double(number):
return number * 2
answer = double(21)
print(answer)This prints 42. Using return is the difference between a function that shows something and one that hands you a value to use later.
Why bother?
Functions help in three big ways:
- Less repeating. Write the code once, use it many times.
- Easier fixing. If there is a bug, you fix it in one place.
- Clearer thinking. A big program becomes a few well-named pieces. This is the idea behind breaking big problems into small ones.
Try these challenges
- Write a function called
cheerthat prints three cheering lines. - Write
square(number)that returns the number multiplied by itself. - Write
shout(word)that prints the word in capital letters. Hint: strings have a method called.upper(). - Write a function that takes a list and prints every item using a loop. (See Python lists for kids.)
Common stumbles
- Forgetting the indent. Everything inside the function must be indented.
- Defining but never calling. If nothing happens, check that you wrote the call.
- Mixing up print and return. If you get
Noneback, the function probably printed instead of returned.
Do not rush this one. Functions are a real step up in abstract thinking, and a child who understands them is well prepared for any language. The Python course introduces them in small steps with plenty of practice.