GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing zetcode.com — Python function - defining and calling functions, arguments, scope Python functionlast modified October 30, 2026 Python 3.15 In this article we cover functions in Python. Python function definitionA function is a named block of code that maps zero or more input parameters to a result. A function is executed only when it is called. The advantages of using functions are:
Functions in Python are first-class citizens. It means that functions have equal status with other objects in Python. Functions can be assigned to variables, stored in collections, or passed as arguments. This brings additional flexibility to the language. Python function types
There are two basic types of functions: built-in functions and user
defined functions. The built-in functions are part of the Python language;
for instance Python creating functions
A function is created with the def function():
pass
The The function is later executed when needed. We say that we call the function. If we call a function, the statements inside the function body are executed. They are not executed until the function is called. myfunc() To call a function, we specify the function name with the round brackets. Calling functionsThe following example defines and calls two functions. ret.py
"""
The ret.py script shows how to work with
functions in Python.
"""
def show_module_doc():
print(__doc__)
def get_module_file():
return __file__
a = show_module_doc()
b = get_module_file()
print(a, b)
The string at the top of the script is called the documentation string. It documents the current script. The file in which we put Python code is called a module.
We define two functions. The first function prints the module
documentation string. The second returns the path of the module. A function
may or may not return a value. If a function does not return a value, it
implicitly returns $ python ret.py The ret.py script shows how to work with functions in Python. None /home/user/python/ret.py Definition before use
A function must be defined before it is called. A func_prec.py
def f1():
print('f1()')
f1()
f2()
def f2():
print('f2()')
The $ python func_prec.py
f1()
Traceback (most recent call last):
File "/home/user/python/func_prec.py", line 6, in <module>
f2()
^^
NameError: name 'f2' is not defined. Did you mean: 'f1'?
Where to define functionsFunctions can be defined inside modules, classes, or other functions. Functions defined inside a class are called methods. defining.py
class Info:
def say(self):
print('This is Info class')
class Some:
@staticmethod
def f():
print('f() static method')
def f():
print('f() plain function')
def g():
def f():
print('f() inner function')
f()
i = Info()
i.say()
Some.f()
f()
g()
In this example we define an $ python defining.py This is Info class f() static method f() plain function f() inner function Python functions are objectsFunctions in Python are objects. They can be manipulated like other objects in Python. fun_obj.py
def f():
"""This function prints a message"""
print('Today it is a cloudy day')
print(isinstance(f, object))
print(type(f))
print(id(f))
print(f.__doc__)
print(f.__name__)
g = f
g()
print(g.__name__)
The $ python fun_obj.py True <class 'function'> 130789884034240 This function prints a message f Today it is a cloudy day f Functions in collectionsFunctions can be stored in collections and passed to other functions. fun_coll.py
def add(x, y):
return x + y
def sub(x, y):
return x - y
def mul(x, y):
return x * y
ops = {'+': add, '-': sub, '*': mul}
for sign, fn in ops.items():
print(f'7 {sign} 3 = {fn(7, 3)}')
def apply(fn, vals):
return [fn(v, v) for v in vals]
print(apply(add, [1, 2, 3]))
print(apply(mul, [1, 2, 3]))
We store three functions in a dictionary and call them by the operator
sign. The $ python fun_coll.py 7 + 3 = 10 7 - 3 = 4 7 * 3 = 21 [2, 4, 6] [1, 4, 9] Three kinds of functions in Python
Looking from a particular point of view, we can discern three kinds of
functions: built-in functions that are always available, functions
contained within modules, which must be imported, and functions defined by
a programmer with the three_kinds.py
from math import sqrt
def cube(x):
return x * x * x
print(abs(-1))
print(cube(9))
print(sqrt(81))
The $ python three_kinds.py 1 729 9.0 Python return keyword
A function is created to do a specific task. Often there is a result from
such a task. The returning.py
def show_message(msg):
print(msg)
def cube(x):
return x * x * x
x = cube(3)
print(x)
show_message('Computation finished.')
print(show_message('Ready.'))
The $ python returning.py 27 Computation finished. Ready. None Returning multiple values
A function can return more than one value. The objects after the
returning2.py
def stats(vals):
mx = max(vals)
mn = min(vals)
total = sum(vals)
return mx, mn, len(vals), total
n = [1, 2, 3, 4, 5]
print(stats(n))
mx, mn, size, total = stats(n)
print(mx, mn, size, total)
The $ python returning2.py (5, 1, 5, 15) 5 1 5 15 Python function redefinitionPython is dynamic in nature. It is possible to redefine an already defined function. redefinition.py
from datetime import datetime
def show_message(msg):
print(msg)
show_message('Ready.')
def show_message(msg):
print(f'{datetime.now():%H:%M:%S} {msg}')
show_message('Processing.')
We define a $ python redefinition.py Ready. 21:21:43 Processing. Python function argumentsMost functions accept arguments. Arguments are values that are sent to the function. The names in the function definition are called parameters. The functions process the values and optionally return some value back. fahrenheit.py
def c2f(c):
return c * 9 / 5 + 32
print(c2f(100))
print(c2f(0))
print(c2f(30))
print(c2f(-40))
In our example, we convert Celsius temperature to Fahrenheit. The
$ python fahrenheit.py 212.0 32.0 86.0 -40.0 Default parameter valuesThe parameters of Python functions may have default values. A default value is used if no argument is provided. default_args.py
def power(x, y=2):
r = 1
for _ in range(y):
r = r * x
return r
print(power(3))
print(power(3, 3))
print(power(5, 5))
Here we created a power function. The $ python default_args.py 9 27 3125 Mutable default values
Default values are evaluated only once, when the mutable_default.py
def add_item(item, items=[]):
items.append(item)
return items
print(add_item('sky'))
print(add_item('owl'))
def add_item2(item, items=None):
if items is None:
items = []
items.append(item)
return items
print(add_item2('sky'))
print(add_item2('owl'))
The $ python mutable_default.py ['sky'] ['sky', 'owl'] ['sky'] ['owl'] Keyword argumentsPython functions can be called with keyword arguments. This means that when calling a function, we specify both the parameter name and a value. When arguments are passed without keywords, the order in which we pass them is crucial. With keywords, the order does not matter. keyword_args.py
def display(name, age, sex):
print(f'Name: {name}, Age: {age}, Sex: {sex}')
display('Lary', 43, 'M')
display(age=24, name='Joan', sex='F')
display('Paul', sex='M', age=31)
The first call uses positional arguments. The second call uses keyword arguments in a different order than the parameters. The third call mixes both: a positional argument may be followed by keyword arguments. $ python keyword_args.py Name: Lary, Age: 43, Sex: M Name: Joan, Age: 24, Sex: F Name: Paul, Age: 31, Sex: M Positional argument after keyword argumentA positional argument cannot follow a keyword argument. keyword_args2.py
def display(name, age, sex):
print(f'Name: {name}, Age: {age}, Sex: {sex}')
display(age=24, name='Joan', 'F')
This is a syntax error; the program is not even started. $ python keyword_args2.py
File "/home/user/python/keyword_args2.py", line 5
display(age=24, name='Joan', 'F')
^
SyntaxError: positional argument follows keyword argument
Positional-only and keyword-only parameters
The special_params.py
def describe(name, /, age, *, city):
print(f'{name} is {age} years old and lives in {city}')
describe('Lucia', 23, city='Bratislava')
describe('Peter', age=41, city='Košice')
try:
describe(name='Jana', age=30, city='Nitra')
except TypeError as e:
print(e)
try:
describe('Martin', 52, 'Žilina')
except TypeError as e:
print(e)
The $ python special_params.py Lucia is 23 years old and lives in Bratislava Peter is 41 years old and lives in Košice describe() got some positional-only arguments passed as keyword arguments: 'name' describe() takes 2 positional arguments but 3 were given Arbitrary number of positional argumentsFunctions in Python can accept an arbitrary number of arguments. arbitrary_args.py
def do_sum(*args):
"""Return the sum of all values"""
print(type(args), args)
r = 0
for i in args:
r += i
return r
print(do_sum.__doc__)
print(do_sum(1, 2, 3))
print(do_sum(1, 2, 3, 4, 5))
print(do_sum())
We use the $ python arbitrary_args.py Return the sum of all values <class 'tuple'> (1, 2, 3) 6 <class 'tuple'> (1, 2, 3, 4, 5) 15 <class 'tuple'> () 0 Arbitrary number of keyword arguments
With the details.py
def display(**details):
print(type(details))
for key, value in details.items():
print(f'{key}: {value}')
display(name='Larry', age=43, sex='M')
We can provide an arbitrary number of key-value arguments. The function handles them all. Dictionaries keep the insertion order, so the arguments are printed in the order in which they were passed. $ python details.py <class 'dict'> name: Larry age: 43 sex: M Combining parameter kinds
The different kinds of parameters can be combined in one function. The
order is: positional parameters, all_kinds.py
def log(level, *args, sep=' ', **kwargs):
print(level, sep.join(map(str, args)), kwargs)
log('INFO', 'server started')
log('WARN', 'disk', 'almost', 'full', sep='_', used='93%')
The $ python all_kinds.py
INFO server started {}
WARN disk_almost_full {'used': '93%'}
Unpacking function return values
Unpacking is cutting an object, such as a list, into its elements. It is
also called destructuring. The unpacking.py
def fn():
return [1, 2, 3, 4, 5, 6]
a, b, c, d, e, f = fn()
print(a, b, c, d, e, f)
a, *mid, b = fn()
print(a, mid, b)
a, b, c, *_ = fn()
print(a, b, c)
a, b, c, *d = fn()
print(a, b, c, d)
*a, b, c, d = fn()
print(a, b, c, d)
We have a function that returns a list of values. First, all six values
are unpacked into six variables. The starred $ python unpacking.py 1 2 3 4 5 6 1 [2, 3, 4, 5] 6 1 2 3 1 2 3 [4, 5, 6] [1, 2, 3] 4 5 6 Unpacking function arguments
We can unpack values into function arguments. The unpacking2.py
def fn(a, b, c, d, e, f):
print(a, b, c, d, e, f)
def fn2(a, b, c, *d):
print(a, b, c, d)
def fn3(a, b, c, *d, e, f):
print(a, b, c, d, e, f)
def user(name, occupation):
print(f'{name} is a {occupation}')
vals = [1, 2, 3, 4, 5, 6]
fn(*vals)
fn2(*vals)
fn3(*vals, e=7, f=8)
data = {'name': 'John Doe', 'occupation': 'gardener'}
user(**data)
We unpack a list into the arguments of three functions. Since the
$ python unpacking2.py 1 2 3 4 5 6 1 2 3 (4, 5, 6) 1 2 3 (4, 5, 6) 7 8 John Doe is a gardener Passing argumentsPython passes arguments by assignment: the parameter becomes a new name for the object that was passed. No copy is made. This is sometimes called call by sharing. passing_args.py
def modify(x):
x.pop()
x.insert(0, 0)
print('Inside modify():', x)
def rebind(x):
x = [10, 20, 30]
print('Inside rebind():', x)
n = [1, 2, 3, 4, 5]
print('Original list:', n)
modify(n)
print('After modify():', n)
rebind(n)
print('After rebind():', n)
The $ python passing_args.py Original list: [1, 2, 3, 4, 5] Inside modify(): [0, 1, 2, 3, 4] After modify(): [0, 1, 2, 3, 4] Inside rebind(): [10, 20, 30] After rebind(): [0, 1, 2, 3, 4] Python local variablesA variable assigned in a function body has a local scope. It is valid only within the body of the function. local_variable.py
name = 'Jack'
def f():
name = 'Robert'
print('Within function', name)
def g():
print('Within function', name)
print('Outside function', name)
f()
g()
print('Outside function', name)
The $ python local_variable.py Outside function Jack Within function Robert Within function Jack Outside function Jack Python global variables
If we want to change a global variable in a function, we must use the
global_variable.py
name = 'Jack'
def f():
global name
name = 'Robert'
print('Within function', name)
print('Outside function', name)
f()
print('Outside function', name)
Using the $ python global_variable.py Outside function Jack Within function Robert Outside function Robert UnboundLocalErrorPython decides at compile time whether a name inside a function is local. A name that is assigned anywhere in the function body is local in the whole body. unbound_local.py
counter = 0
def increment():
counter += 1
try:
increment()
except UnboundLocalError as e:
print(e)
The $ python unbound_local.py cannot access local variable 'counter' where it is not associated with a value Closures and nonlocal
An inner function can use the variables of its enclosing function, even
after the enclosing function has returned. Such a function is called a
closure. To assign to a variable of the enclosing function, we use
the closure.py
def make_counter():
count = 0
def counter():
nonlocal count
count += 1
return count
return counter
c1 = make_counter()
c2 = make_counter()
print(c1(), c1(), c1())
print(c2())
The $ python closure.py 1 2 3 1 Recursive functionsA function can call itself. Such a function is called recursive. A recursive function must have a base case that stops the recursion. recursion.py
import sys
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
print(factorial(5))
print(factorial(20))
print(sys.getrecursionlimit())
The $ python recursion.py 120 2432902008176640000 1000 Function annotationsParameters and return values can be annotated with type hints. The annotations are not enforced by the interpreter; they are used by type checkers, editors, and documentation tools. annotations.py
import inspect
def area(width: float, height: float = 1.0) -> float:
return width * height
def make_user(name: str) -> User:
return User(name)
class User:
def __init__(self, name: str):
self.name = name
print(area(3, 4.5))
print(area('ab', 3))
print(area.__annotations__)
print(inspect.signature(area))
print(make_user.__annotations__)
The $ python annotations.py
13.5
ababab
{'width': <class 'float'>, 'height': <class 'float'>, 'return': <class 'float'>}
(width: float, height: float = 1.0) -> float
{'name': <class 'str'>, 'return': <class '__main__.User'>}
$ python3.13 annotations.py
Traceback (most recent call last):
File "/home/user/python/annotations.py", line 8, in <module>
def make_user(name: str) -> User:
^^^^
NameError: name 'User' is not defined
Python anonymous functions
It is possible to create anonymous functions in Python. Anonymous functions
do not have a name. With the lambda_fun.py
y = 6 z = lambda x: x * y print(z(8)) cs = [-10, 0, 15, 30, 40] ft = map(lambda t: 9 / 5 * t + 32, cs) print(list(ft)) words = ['sky', 'Falcon', 'owl', 'Arrow', 'cup'] print(sorted(words, key=lambda w: w.lower()))
The $ python lambda_fun.py 48 [14.0, 32.0, 59.0, 86.0, 104.0] ['Arrow', 'cup', 'Falcon', 'owl', 'sky'] SourceDefining functions - Python tutorial In this article we covered Python functions. AuthorMy name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming. List all Python tutorials. |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |