Make it reusable
Your own functions
Lesson 5 of 20 · 7 min · Module 2: Loops & functions
Functions turn an idea into a reusable tool. Define one with def, give it a name, and let it return a result.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Define a function with def
- Use a parameter in a calculation
- Return a result for a caller to use
The idea
The function’s body is indented. Use return to provide a value to the caller. You can pass different values into the same function.
def greet(name):
return "Hello, " + name
print(greet("Alex"))
01Definition and execution are different
def creates a function. The function body runs later, when called. Its parameter gets the value supplied by the caller.
def square(number):
return number * number
print(square(4))1602Replace a placeholder with behavior
pass is a valid empty statement that makes the starter syntactically complete. It does not calculate or return a useful value. Replace it with the function’s real work.
Your turn
square(number) to return the number multiplied by itself. Print square(5).What the checks look for
- square(5) returns 25
- Handles zero and negative numbers
- Prints 25
Take this with you
Functions package behavior around an explicit input and output.