Functions turn repeated code into named, reusable tools. They're the single biggest step from "writing lines" to "building programs" — and Python's argument system is richer than most beginners realise.
Define with def name(params):, hand results back with return. Call it with name(args). Parameters can have defaults (def greet(name="Guest")), and callers can name them: greet(name="Ada").
def greet(name):
"""Say hello politely.""" # docstring — describe it!
return f"Hello, {name}!"
message = greet("Ada") # call it — returns a value
print(message) # Hello, Ada!
print(greet("Alan")) # call again — that's the point!print shows a value on screen; return hands it back to the caller so the program can use it. Functions without return give back None.
def add_print(a, b):
print(a + b) # shows 7, returns None
def add_return(a, b):
return a + b # hands 7 back
x = add_print(3, 4) # prints 7
print(x) # None — nothing was returned!
y = add_return(3, 4)
print(y * 10) # 70 — usable resultdef power(base, exponent=2): # default value
return base ** exponent
print(power(5)) # 25 — uses default
print(power(5, 3)) # 125 — positional
print(power(exponent=3, base=2)) # 8 — named, any orderAccept any number of arguments — the pattern behind flexible APIs like print().
def summarize(*nums, **options):
total = sum(nums)
if options.get("average"):
return total / len(nums)
return total
print(summarize(1, 2, 3)) # 6
print(summarize(1, 2, 3, average=True)) # 2.0counter = 0 # global
def bump():
local = 5 # exists only inside bump
return counter + local # reading globals: fine
print(bump()) # 5
# print(local) # NameError — local is gone outsidedouble = lambda x: x * 2 print(double(8)) # 16 # their real home: as arguments words = ["bb", "a", "ccc"] words.sort(key=lambda w: len(w)) print(words) # ['a', 'bb', 'ccc']
def f(items=[]) shares ONE list across all calls — use items=None then items = items or []greet is the function object; greet() actually calls itParameters are the names in the def line; arguments are the actual values you pass when calling. def greet(name) — name is the parameter, "Ada" is the argument.
None. Any function without an explicit return (or with a bare return) hands back None.
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict — letting functions accept flexible inputs.
Only for tiny throwaway functions passed as arguments, like sort keys. If it needs a name or more than one expression, use def.