LearnPy Hub
FunctionsIntermediateLesson 13 of 32

Functions

Watch the ideaA function is a reusable machine
def add(a, b):
    return a + b

total = add(2, 3)
2, 3
add(a, b)
?

Values go in, the function does its work, and a result comes out.

1Level 1 · BasicsBasics

You've been using functions since lesson one: print(), len(), input(). Now you'll write your own. A function is a named, reusable block of code: write it once, use it many times.

Defining and calling a function

def greet():
    print("Hello!")
    print("Welcome to LearnPy Hub")

greet()     # call it
greet()     # and again

def starts a definition, then the name, brackets and a colon. The indented body runs only when you call the function by writing its name with brackets.

Parameters: giving a function input

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

greet("Mim")    # Hello, Mim

name is a parameter, a variable that receives the value you pass in (the argument). A function can take several parameters, separated by commas.

return: giving a value back

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

a = area(4, 5)     # a is 20

return sends a result back to whoever called the function and ends the function immediately. A function without return gives back None. Printing is not returning: printed text just appears on screen, while a returned value can be stored, compared and used in more calculations.

Default and keyword arguments

def power(base, exp=2):       # exp defaults to 2
    return base ** exp

power(5)           # 25
power(2, 10)       # 1024
power(exp=3, base=2)   # 8, arguments by name

Scope: variables inside functions

Variables created inside a function are local: they exist only while the function runs and can't be seen outside it. This keeps functions independent. Pass values in as parameters and get results out with return rather than relying on outside variables.

Docstrings

A string on the first line of a function describes what it does. Tools and help() show it to other programmers.

Key points: def name(params): defines; calling runs it; return sends a value back (otherwise you get None); defaults make parameters optional; variables inside a function are local.

See it in actionA function call gets its own space

When area() is called a new frame appears with w and h. It disappears when the function returns.

Step-by-step

Try it yourselfExample 1: Define and call

The function body runs each time you call it, with different arguments.

example_1.py
Output appears here
Fill in the blanks

Define a greeting

Fill the blanks to define a function and call it, so the program prints Hello, Ayan!.

blanks.py
 greet(name):
    print(f"Hello, {name}!")

("Ayan")

Example 2: Returning values

Returned values can be stored and used in further calculations.

example_2.py
Output appears here
Fill in the blanks

Return the area

Fill the blank so the function gives back the area and the program prints 24.

blanks.py
def area(w, h):
     w * h

print(area(4, 6))

Example 3: Returning several values

Return a tuple and unpack it into separate variables.

example_3.py
Output appears here
Your turn

Biggest of three

Write a function biggest(a, b, c) that returns the largest of three numbers without using max(). Then print biggest(4, 11, 7), which is 11.

my_code.py

Example 4: Print vs return

shout() returns text; say() only prints it and returns None.

example_4.py
Output appears here
Fix the bug

Print is not return

double(5) + 1 should be 11, but the program crashes. Fix the function.

buggy.py

Example 5: Local scope

The x inside the function is a different variable from the x outside it.

example_5.py
Output appears here
Your turn

Is it even?

Write is_even(n) that returns True or False. Read a number and print the result.

Example input10Expected outputTrue

my_code.py

2Level 2 · IntermediateFlexible arguments

*args and **kwargs

def total(*nums): accepts any number of positional values as a tuple. def profile(**info): collects keyword arguments into a dictionary.

Unpacking when calling

f(*my_list) spreads a list into separate arguments; f(**my_dict) spreads a dictionary into keyword arguments.

The mutable default trap

Default values are created once, when the function is defined. def add(item, box=[]): keeps the same list between calls. Use box=None and create the list inside.

Functions are values

You can store functions in a list or dictionary and pass them to other functions, such as a calculator that looks up the operation by name.

See it in actionThe mutable default trap

Watch box keep its old items on the second call.

Step-by-step

Example 6: *args, **kwargs and unpacking

The same function accepts 2 numbers or 20.

example_6.py
Output appears here

Example 7: A calculator built from functions

Add a "pow" entry to the dictionary to support powers.

example_7.py
Output appears here

3Level 3 · AdvancedClosures, keyword-only arguments and type hints

Closures

A function defined inside another remembers the outer variables even after the outer function returns. nonlocal lets it change them. This is how counters and decorators keep state.

Keyword-only and positional-only

Arguments after a lone * must be named: def send(to, *, urgent=False). Arguments before / can't be named. This makes calls clearer and safer.

Type hints and docstrings

def area(w: float, h: float) -> float: documents what goes in and out. Tools like mypy check them; help(area) shows the docstring.

Pure functions

A pure function only uses its inputs and returns a result, without changing anything outside. Pure functions are easy to test and reuse.

See it in actionA closure remembers

Watch each counter keep its own count in its own frame.

Step-by-step

Example 8: Keyword-only arguments and hints

Remove the

example_8.py
Output appears here
Common mistakeForgetting the brackets: greet just names the function, while greet() calls it. And if a function prints its answer instead of returning it, result = f(3) stores None.
Exercise · predict the output

What does this print?

def f(x):
    x * 2
print(f(3))
Quick quiz · 5 questions
1. Which keyword sends a value back from a function?
2. What does a function return if it has no return statement?
3. Given def power(b, e=2), what is power(3)?
4. In def add(a, b), what are a and b called?
5. Can code outside a function use a variable created inside it?
Ready to practice functions?

50 graded problems are waiting in Topic Practice.

Practice this topic →
Python Functions · LearnPy Hub