A function is a named, reusable block of code. You write it once with def, then call it whenever you need it. Functions keep programs short, readable and easy to fix.
DEFINE IT, THEN CALL IT
def cheer():
print("Go, snek, go!")
cheer()
cheer()Go, snek, go!
Go, snek, go!
def only defines the function. Nothing happens until you call it with parentheses: cheer().
PARAMETERS: GIVING IT INPUT
def greet(name):
print("Hi,", name)
greet("Ana")
greet("Ivo")Hi, Ana
Hi, Ivo
name is a parameter, a placeholder. "Ana" is the argument, the real value passed in.
RETURN: GETTING A RESULT BACK
print shows something on the screen. return hands a value back to the code that called the function, so you can store it and keep using it.
def area(width, height):
return width * height
room = area(3, 4)
print(room + 1)13
return it. Print it only at the end.def double(n):
n * 2
print(double(4))n * 2 but never returns it. A function without return gives back None.DEFAULT VALUES
def power_up(hp, bonus=10):
return hp + bonus
print(power_up(50))
print(power_up(50, 25))60
75
If the caller leaves out bonus, Python uses the default 10.
SCOPE: VARIABLES INSIDE STAY INSIDE
def make_score():
score = 100
return score
result = make_score()
print(result)100
score only exists while the function runs. Outside, use the returned value (result), not the inner name.
COMMON BEGINNER MISTAKES
return. The function runs, but the caller gets None.cheer refers to the function; only cheer() runs it.total = add(2, 3) is None if add only prints.def add(a, b=10):
return a + b
print(add(5) + add(1, 1))add(5) uses the default b=10, giving 15. add(1, 1) is 2. 15 + 2 = 17.PRACTICE IT, DON'T JUST READ IT
Function Forest in Snekcade has you build a dice-rolling battle helper out of small functions, with hints when you get stuck.
PLAY FUNCTION FOREST ▸FAQ
What is the difference between print and return in Python?
print shows a value on the screen and the function still gives back None. return sends a value back to the caller so it can be stored in a variable and used later.
Why does my Python function return None?
Because it has no return statement, or the return is never reached. Add return followed by the value you want to give back.
What is a parameter vs an argument?
The parameter is the name in the def line (def greet(name)). The argument is the actual value you pass when calling it (greet("Ana")).