6. Functions
A function is a chunk of code you write once, give a name, and then use as many times as you like. Think of it as a little machine: you put something in, it does a job, and (sometimes) it gives you something back.
Functions stop you repeating yourself, and they keep your code tidy.
Making a function
You build a function with the word def (short for “define”). Then you give it a name, some brackets, and a colon. The code inside is indented, just like with if and for.
Writing this does not run it yet — it just teaches Python the recipe. To actually run it, you call it by writing its name with brackets:
Output:
You can call it as many times as you want:
Output:
Giving a function some information (parameters)
Most functions are more useful if you can hand them some information to work with. The things you hand in go inside the brackets. These are called parameters.
Output:
creature_name is a box that gets filled with whatever you put in the brackets when you call it.
You can have more than one parameter — just separate them with commas:
Output:
Getting an answer back (return)
So far our functions just print things. But often you want a function to work something out and hand the answer back so you can use it later. That’s what return does.
Output:
Here the function took 3, multiplied it by 10, and returned 30. We caught that answer in the gained box.
⚠️ When a function reaches a return, it stops right there and hands back the answer. Nothing after the return inside the function will run.
A function that decides True or False
Functions are great for answering yes/no questions:
Output:
Why functions are so useful
Imagine you work out a creature’s new energy in five different places in your program. Without a function, you’d copy that code five times — and if you needed to fix it, you’d have to fix all five copies!
With a function, you write it once and call it wherever you need it. Fix it in one place, and it’s fixed everywhere. This is one of the most important habits in good programming: don’t repeat yourself.
A word you’ll meet soon: “method”
A function that lives inside a class (you’ll learn about classes next) is called a method. It works exactly the same way — it’s just a function that belongs to an object, like creature.move(). So once you understand functions, you already understand methods. 🎉
✅ Quick recap
- Build a function with
def function_name():and indent the code inside. - Call it by writing its name with brackets:
function_name(). - Hand it information using parameters:
def greet(name): - Use
returnto hand an answer back so you can use it later. - Functions let you write code once and reuse it everywhere.
- A function inside a class is called a method.