def names a reusable block. Arguments go in parentheses. return sends a value back. Without return, the function returns None.
Goal
Define functions with arguments, defaults, and a return value.
A first function
def greet(name):
return f"Hello, {name}"
print(greet("Ada"))
print(greet("Alan"))Defaults
def band(score, pass_mark=90):
if score >= pass_mark:
return "pass"
return "retry"
print(band(91))
print(band(88))
print(band(88, pass_mark=80))Default values are bound once. Do not use a mutable default like [] — pass None and create a list inside.
Several results
def stats(scores):
return min(scores), max(scores), sum(scores) / len(scores)
lo, hi, avg = stats([98, 91, 95, 88])
print(lo, hi, round(avg, 1))*args
def total(*nums):
running = 0
for n in nums:
running += n
return running
print(total(1, 2, 3, 4))
print(total(*[10, 20, 30]))* in a call unpacks a list into arguments.
Docstring
def celsius_to_f(c):
"""Convert Celsius to Fahrenheit."""
return c * 9 / 5 + 32
print(celsius_to_f(0))
print(celsius_to_f.__doc__)Tip
Name functions with verbs: greet, band, total. Names that are only nouns often belong to data (lists, dicts, classes).