Skip to content
Educora
Intermediate17 min9 / 42

Functions

Write your own functions: parameters, returning values with return, default values and variable scope.

Check yourself
In this lesson you will learn
  • Define a function with def and call it
  • Return a result with return and explain how it differs from print
  • Use parameters with default values and keyword arguments
  • Tell local and global variables apart

Imagine you calculate an average in five places in your program, copying the same three lines each time. Then you find a mistake in the calculation — and now you have to fix it in five places! Functions solve this problem: you write the code once, give it a name and call it as often as you like. print(), len() and sum() are functions you already know — now you will create your own.

Defining and calling a function

A function is defined with the word def, followed by the function's name, its parameters in parentheses and a colon. The body of the function is the indented block. Defining a function does nothing by itself; it only runs when you call it by name.

Python
def greet(name):
    print(f'Hello, {name}!')

greet('Aysel')
greet('Murad')
▸ Expected output
Hello, Aysel!
Hello, Murad!
Definition
Parameter and argument

A parameter is the name written in the function definition (name). An argument is the actual value passed to that parameter when the function is called ('Aysel').

return: giving back a result

Usually we want a function to produce a result. return stops the function and sends a value back to the place where it was called. You can store that value in a variable, use it in another calculation or print it. The first line in triple quotes is a docstring: it briefly explains what the function does.

Python
def rectangle_area(width, height):
    """Return the area of a rectangle."""
    return width * height

room = rectangle_area(4, 3.5)
print('Room area:', room)
print('Two rooms:', rectangle_area(4, 3.5) + rectangle_area(3, 3))
▸ Expected output
Room area: 14.0
Two rooms: 23.0

Beginners often mix up print and return. print only writes a value on the screen, while return hands it back to the program. A function without return returns None by default:

Python
def add_print(a, b):
    print(a + b)

def add_return(a, b):
    return a + b

x = add_print(2, 3)
y = add_return(2, 3)
print('x =', x)
print('y =', y)
▸ Expected output
5
x = None
y = 5
add_print wrote 5 on the screen but gave nothing back to x.
F = C · 9/5 + 32F = C · 9/5 + 32
where:
  • Ftemperature in degrees Fahrenheit
  • Ctemperature in degrees Celsius

Let's turn this formula into a function

Python
def celsius_to_fahrenheit(c):
    return c * 9 / 5 + 32

for t in (0, 25, 100):
    print(f'{t} °C = {celsius_to_fahrenheit(t)} °F')
▸ Expected output
0 °C = 32.0 °F
25 °C = 77.0 °F
100 °C = 212.0 °F

Default values and keyword arguments

A parameter can have a default value: if no argument is given in the call, that value is used. You can also pass arguments by name — then their order does not matter and the code is easier to read.

Python
def final_price(price, discount=0):
    return price - price * discount / 100

print(final_price(80))
print(final_price(80, 25))
print(final_price(discount=10, price=50))
▸ Expected output
80.0
60.0
45.0

A function can give back several results at once by returning a tuple. When calling it, we unpack the tuple straight into variables:

Python
def min_max(numbers):
    return min(numbers), max(numbers)

low, high = min_max([12, 5, 27, 9])
print(low, high)
▸ Expected output
5 27

Variable scope

A variable created inside a function is local: it exists only while the function runs and cannot be seen from outside. A variable created outside any function is global. Assigning to a variable with the same name inside a function does not change the global one — it creates a new local variable.

Python
x = 10

def change():
    x = 5
    print('inside:', x)

change()
print('outside:', x)
▸ Expected output
inside: 5
outside: 10
Exercise

Write a function average(numbers) that takes a list and returns the mean of its items. The two print lines in the starter code test it — do not change them.

Exercise · Python
# define average(numbers) here

print(average([4, 5, 3, 5]))
print(average([10, 20]))
▸ Expected output
4.25
15.0
Exercise

Write a function check(score, pass_mark=50) that returns 'passed' if the score is at least the pass mark and 'failed' otherwise. When pass_mark is not given, it is 50. Do not change the three calls in the starter code.

Exercise · Python
# define check(score, pass_mark=50) here

print(check(72))
print(check(45))
print(check(45, 40))
▸ Expected output
passed
failed
passed

Key points

  • A function is defined with def name(parameters): and called by its name.
  • return sends a value back to the caller; without return the result is None.
  • print writes on the screen; return gives the value to the program.
  • Default values (discount=0) make an argument optional.
  • Variables inside a function are local and not visible outside it.

Check yourself

10 questions. Every correct answer earns XP.

1 / 10
Which keyword defines a function in Python?