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
def saluta(nome):
return f"Ciao, {nome}!"
saluta("Ada") # 'Ciao, Ada!'defintroduces the function, followed by the name and the parameters in parentheses.- The
:opens the indented block. returnsends 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:
def stampa_e_basta(x):
print(x)
risultato = stampa_e_basta("ciao")
# prints 'ciao'
print(risultato) # NoneA bare return (no value) also returns None, but it can serve as an early
exit:
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).
def divisione_resto(a, b):
return a // b, a % b
quoziente, resto = divisione_resto(17, 5)
# 3, 2Docstring: built-in documentation
The first string inside the function is the docstring: it shows up in
help(fn) and as a tooltip in IDEs.
def area_cerchio(raggio):
"""Calcola l'area di un cerchio dato il raggio."""
import math
return math.pi * raggio ** 2Scope: local variables
Variables defined inside a function are local: they don't exist outside.
def f():
x = 10
return x
f() # 10
x # NameError: name 'x' is not definedFunctions 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
Define a function `double(x)` that returns `x * 2`. Then call it with 7 and assign the result to `result`. Evaluate `result`.
Show hint
Use return x * 2.
Solution available after 3 attempts
Review exercise
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)`.
Show hint
return min(nums), max(nums)
Solution available after 3 attempts
Additional challenge
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.
Show hint
Use slicing text[::-1] to reverse the string and compare it with the original text.
Solution available after 3 attempts