Lesson 61 +10 XP

Functions

Functions

A function is a named block of code you can run again and again.

Define and call

def my_function():
    print("Hello from a function")

my_function()  # Hello from a function

def defines it; the name followed by () calls it.

Arguments

Pass values in parentheses:

def greet(name):
    print("Hello " + name)

greet("Ada")  # Hello Ada

Parameters vs arguments

  • Parameter: the variable in the definition (name).
  • Argument: the value you pass when calling ("Ada").

Number of arguments must match

def full(fname, lname):
    print(fname + " " + lname)

full("Emil", "Refsnes")  # ok
full("Emil")  # TypeError: missing argument

Return a value

return sends a result back:

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

print(add(5, 3))  # 8

pass as a placeholder

def empty():
    pass

TL;DR

  • def name(): defines; name() calls.
  • Arguments go in parentheses; counts must match.
  • return gives back a value.
  • A function without return gives None.