Functions in Python

by Alex
Functions in Python

Python includes many built-in functions. Such functions perform a predetermined task and can be called as needed in any program. However, if you can’t find a built-in function that can solve your problem, you can always write a suitable one yourself. We will now look at how to define and use functions in a Python program.

Defining a Function

A function is a reusable block of program instructions designed to perform a specific task. Python uses the keyword def to define a function. Below is the syntax for defining a function. Syntax:
def function_name(parameters):
"""docstring"""
instruction1
instruction2
...
...
return [expression]
The keyword def is followed by a suitable identifier (function name) and parentheses. The parentheses may additionally contain one or more parameters. The symbol ‘:’ after the parentheses starts an indented block (function body). The first instruction in the body of a function can be a string called docstring. It describes the functionality of the function/class. The docstring is optional. In general, the body of a function contains one or more instructions that perform some actions. It may also contain the pass keyword. The last instruction in a function block is often the return instruction. It returns control back to the environment that called the function. If the return statement is followed by an expression, its value is also passed to the calling code. The following example defines the welcome() function. An example of a user-created function:
def welcome():
"""This function prints 'Welcome!'""
print('Welcome!')
Above we have defined the welcome() function. The first instruction is a docstring, which tells us what this function does. The second is the print method that prints the specified string to the console. Note that welcome() does not contain the return operator. To call a previously defined function, simply use an expression consisting of its name and two parentheses ‘()’ anywhere in the code. For example, the above function can be called as: welcome(). An example of a user-defined function call:
welcome()
Conclusion:
Welcome!
By default, all functions return None if there is no return operator.
returned_value = welcome()
print(returned_value)
Output:
Welcome!
None
The help() function outputs a docstring, as shown below.
>>> help(welcome)
Help on function welcome in module __main__:
welcome()
This function prints 'Welcome!'

Function Parameters

Functions can also take one or more parameters (aka arguments) as input and use them to perform the computations defined within the function block. In this case, the parameters/arguments are given appropriate formal names. As an example, let’s change the welcome() function: it now takes the string user_name as a parameter; the print() instruction has also been changed to display a more personalized welcome. Example function with arguments:
def welcome(user_name):
print('Welcome, ' + user_name + '!')
welcome('Anon') # function call with parameter
Output:
Welcome, Anon!
The named arguments used in the function definition are called formal parameters. In turn, the objects passed to the function when it is called are called actual arguments/parameters. Function parameters can be annotated to indicate the type of the argument using the parameter:type syntax. For example, the following annotation specifies the type of the parameter string. An example of using type annotation:
def welcome(user_name:str):
print('welcome, ' + user_name + '!')
welcome('Anon') # pass the string to the function
# will pass normally
welcome(42) # but passing a number into the
# function will cause an error

Passing multiple parameters

A function can have many parameters. The welcome() variation below takes three arguments. An example definition of a function with multiple parameters:
def welcome(first_name:str, last_name:str):
print('welcome, ' + first_name + ' + last_name + '!')
welcome('Anton', 'Chekhov') # pass arguments to function
Output:
Welcome, Anton Chekhov!

Unknown number of arguments

A function in Python can have an unknown number of parameters. Specify * in front of the argument if you do not know how many parameters the user will pass. An example of a function with an unknown number of parameters (only the first 3 are used):
def welcome(*name_parts):
message = 'Welcome, ' + name_parts[0] + "
message += name_parts[1] + " + name_parts[2]
print(message + "!")
welcome('Anton', 'Pavlovich', 'Chekhov')
Conclusion:
Welcome, Anton Pavlovich Chekhov!
The following function works with any number of arguments. An example of a function that uses all the parameters passed to it:
def welcome(*name_parts):
message = 'Welcome,'
for part in name_parts:
message += " + part
print(message + "!")
welcome('Anton', 'Pavlovich', 'Chekhov,
'and', 'Fyodor', 'Mikhailovich', 'Dostoevsky')
Conclusion:
Welcome, Anton Pavlovich Chekhov and Fyodor Mikhailovich Dostoevsky!

Keyword arguments

To use a function with parameters, you must provide it with the number of actual arguments corresponding to the number of formal arguments. On the other hand, when calling a function, we are not obliged to observe the order of parameters specified in the definition. But in this case, when passing the argument values, we should explicitly specify the names of the corresponding formal parameters. In the following example, the actual values are passed using parameter names.
def welcome(first_name:str, last_name:str):
print(‘welcome, ‘ + first_name + ‘ + last_name + ‘!’)
welcome(last_name=’Chekhov’, first_name=’Anton’) # transfer
# arguments into the function in any order
Output:
Welcome, Anton Chekhov!

Argument-keywords **kwarg

A function can have only one parameter prefixed with **. It initializes a new ordered mapping (dictionary) containing all the keyword arguments left without a corresponding formal parameter. An example of using **kwarg:
def welcome(**name_parts):
print('welcome, ' + name_parts['first_name'] + ' + name_parts['last_name'] + '!')
welcome(last_name='Chekhov', first_name='Anton')
welcome(last_name='Chekhov', first_name='Anton', age='28')
welcome(last_name='Chekhov') # will cause KeyError
Conclusion:
Welcome, Anton Chekhov!
Welcome, Anton Chekhov!
When using the ** parameter, the order of the arguments is irrelevant. However, their names must be identical. The keyword arguments can be accessed to get the passed values using this expression: parameter_name_kwarg[‘passed_argument_name’]. If a function accesses a keyword argument but the calling code does not pass this parameter, it will raise a KeyError exception, as shown below. An example of a function that invokes a KeyError:
def welcome(**name_parts):
print('welcome, ' + name_parts['first_name'] + ' + name_parts['last_name'] + '!')
welcome(last_name='Chekhov') # causes KeyError: the 'first_name' argument must be provided
Output:
Traceback (most recent call last):
...
line 2, in welcome
print("Welcome, ' + name_parts['first_name'] + ' + name_parts['last_name'] + '!")
KeyError: 'first_name'

Parameters with default value

When a function is defined, its parameters can be assigned default values. Such a value is replaced by the corresponding actual argument if it was passed when the function was called. However, if the actual parameter was not provided, the default value will be used within the function. The welcome() function shown below is defined with the name parameter, which has a default value of ‘Anon’. It will only be replaced if any actual argument is passed by the caller. An example of a function with a default value:
def welcome(user:str = 'Anon'):
print('welcome, ' + user + '!')
welcome()
welcome('Chekhov')
Conclusion:
Welcome, Anon!
Welcome, Chekhov!

A function with a return value

In most cases, we need the result of a function to be used in further calculations. Therefore, when a function finishes executing, it should also return some result value. In order to pass such a value to external code, the function must contain an instruction with the return operator. In this case, the return value must be specified after return. An example of a function with a return value:
def get_product(a, b):
return a * b
The following shows how to get the result of the get_product() function when you call it. An example of using a function with a return value:
result = get_product(6, 7)
print(result)
result = get_product(3, get_product(4, 5))
print(result)
Output:
42
60

Related Posts

LEAVE A COMMENT