Functions and print

Functions

A function is a named, reusable block of code. Define one with def, give it a name and parameters, and put its logic in an indented block underneath:

def square(n):
    return n * n

Call it by name with the arguments it expects:

>>> square(5)
25

return vs print

This is the single most important distinction in this lesson, and the one place beginners most often trip up.

  • return hands a value back to the caller so it can be used elsewhere — stored in a variable, passed to another function, compared, etc.
  • print just displays text on the screen. It doesn't give the caller anything to work with.
def add_v1(a, b):
    print(a + b)   # displays the sum, but gives the caller nothing

def add_v2(a, b):
    return a + b    # hands the sum back

result = add_v1(2, 3)   # prints "5", but result is None!
result = add_v2(2, 3)   # result is 5

In every problem in this course, when you're asked to "write a function that returns X", you need an actual return statement — printing the right-looking value will not pass the tests, because the test harness checks what your function returns, not what it prints.

(There are a few problems later that specifically test what gets printed — those will say so explicitly.)

Parameters and arguments

A function can take any number of parameters:

def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

greet("Ada")               # "Hello, Ada!"
greet("Ada", "Hi")         # "Hi, Ada!"
greet("Ada", greeting="Yo") # "Yo, Ada!"

greeting="Hello" gives that parameter a default value — callers can leave it out entirely, or override it either positionally or by name.

You now have everything you need for the first few problems: variables, arithmetic, and functions that return a value.