Python for beginners · Lesson 12 of 15
Functions: write your own commands
Define functions with def, pass in parameters, send results back with return, give parameters default values and understand local variables.
You have used many functions already: print(), len(), round(). A function is a named block of code that you can run whenever you need it. Writing your own functions saves you from repeating code and splits a big program into small, readable pieces.
def (functions) creates a function: the word def, a name, round brackets and a colon, then the indented body. Defining a function does not run it. The body runs each time you call the function by writing its name with brackets.
def greet():
print("Hello!")
print("Welcome to the course.")
greet()
greet()Hello! Welcome to the course. Hello! Welcome to the course.
Parameters
Parameters are names in the brackets that receive values when the function is called. The values you pass in are called arguments. A function can have as many parameters as it needs, separated by commas.
def greet(name, city):
print(f"Hello, {name} from {city}!")
greet("Ana", "Porto")
greet("Kenji", "Osaka")Hello, Ana from Porto! Hello, Kenji from Osaka!
Sending a result back with return
return statement ends the function and hands a value back to the line that called it, where you can store it, print it or calculate with it. A function without return gives back None, Python's value for "nothing".
def area(width, height):
return width * height
kitchen = area(3, 4)
bedroom = area(4, 5)
print(kitchen, bedroom)
print("Total:", kitchen + bedroom)
def add_and_print(a, b):
print(a + b)
result = add_and_print(2, 3)
print(result)12 20 Total: 32 5 None
add_and_print shows 5 but returns nothing, so result is None.
Default values and keyword arguments
A parameter can have a default value that is used when the caller leaves it out. When calling, you can also name the arguments (rate=0.1), which makes calls easier to read and lets you skip the order.
def price_with_vat(price, rate=0.2):
return round(price * (1 + rate), 2)
print(price_with_vat(100))
print(price_with_vat(100, 0.1))
print(price_with_vat(rate=0.24, price=50))120.0 110.0 62.0
def stats(numbers):
return min(numbers), max(numbers), sum(numbers) / len(numbers)
low, high, average = stats([4, 8, 15, 16, 23, 42])
print(low, high, average)4 42 18.0
Separate several return values with commas: they come back as a tuple, which you can unpack.
Scope: variables inside functions
Variables created inside a function are local: they exist only while the function runs and do not touch variables with the same name outside. A function can read variables from outside, but assigning to a name inside a function creates a new local one.
total = 100
def add_bonus():
total = 5
print("Inside:", total)
add_bonus()
print("Outside:", total)
rate = 0.2
def tax(amount):
return amount * rate
print(tax(50))Inside: 5 Outside: 100 10.0
✎ Exercise
Write a function shipping_cost(weight, express=False). Parcels up to 1 kg cost 4.0, up to 5 kg cost 7.5, heavier ones 12.0. Express shipping doubles the price. Return the cost and test it with the three calls below.
Hint: Use if / elif / else to set cost, then a second if for express, then return cost.
def shipping_cost(weight, express=False):
# your code here
return 0
print(shipping_cost(0.5))
print(shipping_cost(3))
print(shipping_cost(8, express=True))
Expected output:
4.0 7.5 24.0
Show a solution
def shipping_cost(weight, express=False):
if weight <= 1:
cost = 4.0
elif weight <= 5:
cost = 7.5
else:
cost = 12.0
if express:
cost = cost * 2
return cost
print(shipping_cost(0.5))
print(shipping_cost(3))
print(shipping_cost(8, express=True))4.0 7.5 24.0
Check yourself
1. What does a function return if it has no return line?
Without return, every function gives back None.
2. With def f(a, b=2): return a * b, what is f(5)?
b was not given, so it uses its default 2: 5 * 2 = 10.
3. A function sets x = 1 inside its body. What happens to a variable x outside the function?
The x inside the function is local. The outer x is a different variable and does not change.