Making and calling a function
Write def, a name, brackets and a colon. The indented lines underneath are the function's body. They run when you call the function.
def say_hi():
print("Hi!")
say_hi()
say_hi()Hi! Hi!
Arguments
Names inside the brackets are parameters. When you call the function, the values you pass in, called arguments, get stored in them.
def greet(name):
print("Hi, " + name)
greet("Sam")
greet("Ana")Hi, Sam Hi, Ana
return
return sends a value back to where the function was called. The function stops as soon as it returns.
def double(n):
return n * 2
print(double(4) + 1)9
Try it
What does this print?
def square(n):
return n * n
print(square(3) + square(1))
Default values
A parameter can have a default. If the caller leaves it out, the default is used.
def greet(name="friend"):
return "Hi, " + name
print(greet())
print(greet("Sam"))Hi, friend Hi, Sam
Try it
What does this print?
def welcome(place="home"):
return "Welcome " + place
print(welcome("back"))
Printing is not returning
If a function prints a value but doesn't return it, you get None back. None is Python's way of saying "nothing".
def add(a, b):
print(a + b)
result = add(2, 3)
print(result)5 None
Try it
In the add example, what is stored in result?
Common mistakes
Python reads top to bottom. If you call greet() above the def greet line, you get a NameError.
say_hi on its own doesn't run anything. You need say_hi().
A function that calculates a value but doesn't return it gives back None.
Recap
- def makes a function. Its body is indented.
- Parameters receive the arguments you pass in.
- return sends a value back and ends the function.
- No return means the function gives back None.