note.nkmk.me

Define and call functions in Python (def, return)

Posted: 2019-06-24 / Tags: Python

This post describes how to define and call (execute) functions in Python.

  • Basics of function definition and call in Python
  • Arguments
    • Positional argument
    • Keyword argument
    • Default argument
    • Variable-length argument
      • *args: Receive multiple arguments as a tuple
      • **kwargs: Receive multiple keyword arguments as a dictionary
    • Expand lists and dictionaries (Unpacking)
  • Return value
    • Multiple return values

See the following post for lambda expressions that are used to create anonymous functions.

The official documentation for function definition is:

Sponsored Link

Basics of function definition and call in Python

In Python, functions are defined in blocks of def statements as follows:

def functionn_name():
    do_something

When calling, write the function name as it is.

function_name()

Here is an example of a simple function definition and call: The defined process is executed.

def hello():
    print('Hello')

hello()
# Hello

The basic form to specify arguments and return value is as follows.

Define function:

def functionn_name(param1, param2...):
    do_something
    return return_value

Call function:

function_name(arg1, arg2...)

Example:

def add(a, b):
    return a + b

x = add(3, 4)
print(x)
# 7

Details on the arguments and return values are described below.

Note that while it is recommended to leave two lines before and after the def block in the Python coding standard PEP8, in the sample code only one line is left for convenience.

Arguments

Positional argument

Specify arguments separated by commas in parentheses of function_name().

def print_add(a, b, c):
    print('a = ', a)
    print('b = ', b)
    print('c = ', c)
    print('a + b + c = ', a + b + c)

When calling, specify the values in the defined order.

print_add(1, 10, 100)
# a =  1
# b =  10
# c =  100
# a + b + c =  111

If the number of values specified at function call does not match the number of arguments at function definition, TypeError will occur.

# print_add(1)
# TypeError: print_add() missing 2 required positional arguments: 'b' and 'c'

# print_add(1, 10, 100, 1000)
# TypeError: print_add() takes 3 positional arguments but 4 were given

Keyword argument

It is possible to specify a value as argument_name=value when calling a function. In this case, they can be specified in any order.

print_add(b=10, c=100, a=1)
# a =  1
# b =  10
# c =  100
# a + b + c =  111

It is not necessary to specify all the arguments by keywords, but can be specified by keywords after specifying by position. However, all arguments after the arguments specified in keywords must be specified by keywords.

print_add(1, c=100, b=10)
# a =  1
# b =  10
# c =  100
# a + b + c =  111

# print_add(a=1, 10, 100)
# SyntaxError: positional argument follows keyword argument

Default argument

The default value of the argument can be set by defining argument_name=default_value at function definition.

If default value is set, specification of argument can be omitted when calling function.

def print_add_default(a, b, c=100):
    print('a = ', a)
    print('b = ', b)
    print('c = ', c)
    print('a + b + c = ', a + b + c)

print_add_default(1, 10)
# a =  1
# b =  10
# c =  100
# a + b + c =  111

Of course, if you specify another value, that value will be used.

print_add_default(1, 10, 200)
# a =  1
# b =  10
# c =  200
# a + b + c =  211

Placing a default argument before an ordinary argument (arguments without a default value) at function definition causes a SyntaxError.

# def print_add_default(a=1, b, c=100):
#     ...
# SyntaxError: non-default argument follows default argument

Note that if you use a list or a dictionary as default values, the same objects will always be used as when calling a function. See the following post for details.

Variable-length argument

If you add * and ** to argument names when defining a function, it becomes a variable-length argument, and you can specify any number of arguments when calling a function.

By convention, the names *args and **kwargs are often used, but as long as * and ** are headed, there are no problems with other names.

*args: Receive multiple arguments as a tuple

If you put * at the beginning of the name, multiple arguments will be received as a tuple.

def func_args(*args):
    print(args)

func_args(1, 10)
# (1, 10)

func_args(1, 10, 100, 1000)
# (1, 10, 100, 1000)

**kwargs: Receive multiple keyword arguments as a dictionary

If you put ** at the beginning of the name, multiple keyword arguments will be received as a dictionary (dict).

def func_kwargs(**kwargs):
    print(kwargs)

func_kwargs(a=1, b=10)
# {'a': 1, 'b': 10}

func_kwargs(c=1, b=10, d=1000, a=100)
# {'c': 1, 'b': 10, 'd': 1000, 'a': 100}

Be careful about the order when combining with positional arguments or combining with *args and **kwargs. See the following post for details.

Expand lists and dictionaries (Unpacking)

Expand lists or tuples

If you add * to a list or tuple when calling a function, the elements are expanded and specified in order as positional arguments. TypeError will occur if the number of elements and the number of arguments do not match.

def print_add(a, b, c):
    print('a = ', a)
    print('b = ', b)
    print('c = ', c)
    print('a + b + c = ', a + b + c)

l = [1, 10, 100]

print_add(*l)
# a =  1
# b =  10
# c =  100
# a + b + c =  111

l = [1, 10]

# print_add(*l)
# TypeError: print_add() missing 1 required positional argument: 'c'

Expand dictionaries

If you add ** to the dictionary when calling a function, the key of the element is expanded as an argument name, and the value is expanded as an argument value and specified as keyword arguments. If there is no key that matches the argument name, or if there is a key that does not match the argument name, TypeError will occur.

d = {'a': 1, 'b': 10, 'c': 100}

print_add(**d)
# a =  1
# b =  10
# c =  100
# a + b + c =  111

d = {'a': 1, 'b': 10, 'x': 100}

# print_add(**d)
# TypeError: print_add() got an unexpected keyword argument 'x'

See the following post for notes on combining default arguments or variable-length arguments.

Sponsored Link

Return value

The return value of the function is specified by the return statement.

def func_return(a, b):
    return a + b

x = func_return(3, 4)

print(x)
print(type(x))
# 7
# <class 'int'>

The type of return value depends on the type of argument and the processing performed by the function.

x = func_return(0.3, 0.4)

print(x)
print(type(x))
# 0.7
# <class 'float'>

Multiple return values

Specifying multiple values separated by commas after return will return a tuple.

def func_return_multi(a, b):
    return a + b, a * b, a / b

x = func_return_multi(3, 4)

print(x)
print(type(x))
# (7, 12, 0.75)
# <class 'tuple'>

It is possible to unpack each value and assign it to each variable.

x, y, z = func_return_multi(3, 4)

print(x)
print(y)
print(z)
# 7
# 12
# 0.75

If you enclose it in [], a list is returned instead of a tuple.

def func_return_multi_list(a, b):
    return [a + b, a * b, a / b]

x = func_return_multi_list(3, 4)

print(x)
print(type(x))
# [7, 12, 0.75]
# <class 'list'>

x, y, z = func_return_multi_list(3, 4)

print(x)
print(y)
print(z)
# 7
# 12
# 0.75
Sponsored Link
Share

Related Categories

Related Posts