Skip to main content
eLearner.app
Module 5 · Lesson 1 of 417/36 in the course~12 min
Module lessons (1/4)

def and return

A function is a reusable block of code: you define it once with def, then call it as many times as you want. Functions make code modular, testable, and self-documenting.

Basic syntax

Python
def saluta(nome):
    return f"Ciao, {nome}!"

saluta("Ada")     # 'Ciao, Ada!'
  • def introduces the function, followed by the name and the parameters in parentheses.
  • The : opens the indented block.
  • return sends a value back to the caller and ends the function.

Explicit return vs implicit None

If you don't write return, the function returns None implicitly:

Python
def stampa_e_basta(x):
    print(x)

risultato = stampa_e_basta("ciao")
# prints 'ciao'
print(risultato)   # None

A bare return (no value) also returns None, but it can serve as an early exit:

Python
def primo_pari(nums):
    for n in nums:
        if n % 2 == 0:
            return n
    return None   # explicit: communicates "not found"

Multiple values? Return a tuple

Python has no "out parameters": to return more than one thing, return a tuple (often unpacked by the caller).

Python
def divisione_resto(a, b):
    return a // b, a % b

quoziente, resto = divisione_resto(17, 5)
# 3, 2

Docstring: built-in documentation

The first string inside the function is the docstring: it shows up in help(fn) and as a tooltip in IDEs.

Python
def area_cerchio(raggio):
    """Calcola l'area di un cerchio dato il raggio."""
    import math
    return math.pi * raggio ** 2

Scope: local variables

Variables defined inside a function are local: they don't exist outside.

Python
def f():
    x = 10
    return x

f()    # 10
x      # NameError: name 'x' is not defined

Functions always return something

In Python, if a function does not explicitly declare a return statement or features an empty return, it will implicitly return the special value None. There are no functions that do not return a value.

Try it

Exercise#python.m5.l1.e1
Attempts: 0Loading…

Define a function `double(x)` that returns `x * 2`. Then call it with 7 and assign the result to `result`. Evaluate `result`.

Loading editor…
Show hint

Use return x * 2.

Solution available after 3 attempts

Review exercise

Exercise#python.m5.l1.e2
Attempts: 0Loading…

Define `min_max(nums)` that returns a tuple `(minimum, maximum)`. Call it on `[3, 1, 4, 1, 5, 9, 2, 6]` and unpack the result into `mn, mx`. Evaluate `(mn, mx)`.

Loading editor…
Show hint

return min(nums), max(nums)

Solution available after 3 attempts

Additional challenge

Exercise#python.m5.l1.e3
Attempts: 0Loading…

Define a function `is_palindrome(text)` that returns `True` if the input string is equal to its reversed version, and `False` otherwise. Test the function with `is_palindrome("radar")` as the last expression.

Loading editor…
Show hint

Use slicing text[::-1] to reverse the string and compare it with the original text.

Solution available after 3 attempts