Functions
Functions
return sends a value back to the caller. The caller can print it, store it, or pass it to another function.
Source
def greet(name):
return f"Hello, {name}."
print(greet("Python"))Output
Hello, Python.Default arguments provide common values. Keyword arguments make it clear which option is being overridden.
Source
def format_total(amount, currency="USD"):
return f"{amount} {currency}"
print(format_total(10))
print(format_total(10, currency="EUR"))Output
10 USD
10 EURA function without an explicit return returns None. That makes side-effect-only functions easy to distinguish from value-producing ones.
Source
def log(message):
print(f"log: {message}")
result = log("saved")
print(result)Output
log: saved
NoneMutable default arguments are evaluated once when the function is defined, not on each call. The same list is shared across calls, so successive calls see each other's mutations. Use None as the sentinel and create a fresh container inside the body.
Source
def append_broken(item, items=[]):
items.append(item)
return items
print(append_broken("a"))
print(append_broken("b"))
def append_fixed(item, items=None):
if items is None:
items = []
items.append(item)
return items
print(append_fixed("a"))
print(append_fixed("b"))Output
['a']
['a', 'b']
['a']
['b']Notes
- Use
returnfor values the caller should receive. - Defaults keep common calls concise.
- Keyword arguments make options readable at the call site.
- Never use a mutable value as a default argument; use
Noneand build the container inside the function body.
See also
- prerequisite: Variables
- related: Args and Kwargs
- related: Keyword-only Arguments
- related: Closures
Run the complete example
Expected output
Hello, Python.
10 USD
10 EUR
log: saved
None
['a']
['a', 'b']
['a']
['b']
Execution time appears here after you run the example.