Programming and IT
Python: functions
A function is a named piece of code that takes values and returns a result. In Python a definition takes one line, but arguments have subtleties: defaults are evaluated once, positional and keyword arguments mix by rules, and a function without return still returns something.
In this article
Definition and return#
A function starts with the word def, a name, parentheses with the parameter
list and a colon. The body is indented by four spaces.
"""Return a greeting for the given name."""
return f
# Hello, Anna!
The triple-quoted string right under def is the function's docstring; it is
available through help(greet) and greet.__doc__. Writing one pays off even
for yourself: a month later it is the only way to remember what the function
promises.
If no return runs, the function returns None — nothing crashes, the result is
simply empty:
# prints, but does not return
= # 5
# None
Mixing up print and return is beginner mistake number one. print shows a
value to a person; return hands it to the code.
Arguments: positional, keyword, with defaults#
return **
# 9
# 27
# 8
Positional arguments are matched by order, keyword arguments by name, and the
latter can come in any order. Parameters with default values are declared only
after the ordinary ones: def f(a=1, b) is a syntax error.
An asterisk in the parameter list makes everything after it keyword-only — that
saves you from unreadable calls like save(data, True, False):
return f
# report / overwrite: True
A variable number of arguments#
*args collects extra positional arguments into a tuple, and **kwargs collects
keyword arguments into a dictionary.
return
# (1, 2, 3) {'discount': 5}
# 6
The same asterisk works in a call too — it unpacks a ready sequence or dictionary into arguments:
=
# 8
# 125
The mutable default value#
A default expression is evaluated once — when the function is defined, not on every call. So a list or dictionary used as a default lives on between calls:
return
# ['a']
# ['a', 'b'] — not what you expected
The fix is always the same: use None as the default and create the real value
inside.
=
return
# ['a']
# ['b']
Scope#
A name assigned inside a function is treated as local for the whole function — even if the assignment is on the last line.
= 0
global
+= 1
# 1
Without the global counter line, the same code would fail with
UnboundLocalError. But global is a bad habit: more often you should take the
value as an argument and return the new one. Reading global values inside a
function works without any declaration.
A little practice: write a function stats(*numbers) that returns a tuple of the
minimum, maximum and mean, and check that it works both as stats(1, 2, 3) and as
stats(*[1, 2, 3]). Next you will want Python decorators
— they are add-ons built on top of functions — and
Python exceptions, to report bad arguments cleanly.
Step-by-step plan
- A simple function with returnWrite a function that takes two numbers and returns their sum; print the result.
- Defaults and keyword argumentsAdd a parameter with a default value and call the function three different ways.
- Collect *argsA function with a variable number of arguments that computes the mean; call it by unpacking a list.
- Reproduce the trapRun the box=[] example twice in a row and see the list accumulate values.
- Rewrite it safelyChange the default to None and check that calls no longer affect each other.
Learn in SKILLOK edu
Courses, lessons and assignments with review.
Check yourself
1.What does this print: def f(a, b=2): return a * b; print(f(3))?
2.What does this print: def f(x): print(x); r = f(1); print(r)?
3.What does the second call print: def c(i, box=[]): box.append(i); return box; c('a'); print(c('b'))?
4.What does this return: def t(*args): return len(args); t(1, 2, 3, 4)?
Sources
-
Python tutorial: defining functionsThe section on def, defaults, *args and **kwargsfree
-
Built-in functions referencesum, min, max, sorted and other functions to check your solutions withfree
-
PEP 8 — Style GuideHow to name functions and parametersfree
Was this helpful?