Functions, and return vs print

You have been using functions since lesson 1. Now you make your own with def:

def greet(name):
    return f"Hi {name}!"

name is a parameter: a variable that gets its value when the function is called. greet("Zoe") runs the body with name set to "Zoe". The value you pass in ("Zoe") is called an argument. Defining a function does not run it; it only runs when you call it.

Now the most important idea in this lesson: return is not print.

  • print shows something on the screen. That is it. The program cannot use what was printed.
  • return hands a value back to the code that called the function, so you can store it, do maths with it, or pass it on. It also ends the function immediately.
def double_print(x):
    print(x * 2)

def double_return(x):
    return x * 2

a = double_print(5)    # shows 10, but a is None
b = double_return(5)   # shows nothing, but b is 10

A function with no return gives back None, Python's "nothing here" value. If you ever see a mysterious None in your output, a missing return is the prime suspect.

Rule of thumb: functions that compute something should return it, and let the caller decide whether to print. That makes them reusable and testable. The exercises here are checked with tests that call your function and look at what it returns, so printing will not pass.

Variables created inside a function are local: they exist only while the function runs and are invisible outside it.

Try it yourself

Edit it. Break it. Run it again.
def greet(name):
    return f"Hi {name}!"

def area(width, height):
    return width * height

message = greet("Zoe")
print(message)
print("Room:", area(4, 3) + area(2, 2), "square metres")

def double_print(x):
    print(x * 2)

result = double_print(5)
print("result is", result)
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

Your turn

Type it yourself. That is the whole trick.

1Add them up

Write a function add(a, b) that returns the sum of a and b. Do not print inside it.

def add(a, b):
    print(a + b)
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

2Biggest of three

Write biggest(a, b, c) that returns the largest of the three numbers. Try it with if statements instead of using max().

def biggest(a, b, c):
    return a
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.