Functions in Python 3

by Alex
Functions in Python 3

Functions are an important component of any language, and Python is no exception. You can’t do without functions when writing any major project, so every programmer needs to know how to work with them.

What is a Function?

A function is a block of code that can be called repeatedly for execution. It is a fundamental part of any programming language.

A function allows you to divide a program into independent but related parts. Programmers use functions to make a program modular and avoid code repetition.

A function can be used to process data; it takes a value as input, processes it, and returns the result to the program. It may also not return a value, but display it on the screen or write it to a file. The programmer can write his own function or use ready-made language solutions, if they are available, of course. For example, it is better not to write your own function to determine the maximum number, but use the standard max().


When declaring a function, we have to follow certain rules:

  • The declaration is done with the keyword def, followed by the function name and parentheses ().
  • The arguments passed to the function must be in parentheses. There you can also define their default values, specifying them after the equal sign.
  • Before the main content, it is desirable to include a documentation line (docstring), which usually describes the purpose and basic principles of the function.
  • The body of the function begins after the colon character. It is important not to forget the indentation.
  • To exit a function in Python, use the return [value] operator. If the operator is omitted, a value of None will be returned.

A function can be declared anywhere: inside a module, a class, or another function. If it is declared inside a class, it is called a class method and is called as: class_name.function().

The syntax of the declaration

Parameters (arguments) must be passed in the order in which they are defined in parentheses.

def Name(arguments):
    return [value]

Code Example

The function adds the two numbers passed in as arguments. If one or both arguments were not passed, the default values are used.

def print_sum(a = 2, b = 2):
    sum = a + b
    return # will return None


Once a function has been defined, it can be called anywhere in the script, either in the body of the script itself or in the body of another function:

# define the function
def print_sum(a = 2, b = 2):
    sum = a + b
# call it
print_sum(5, 1)

The value of the function can be passed directly to a variable or to another function:

def sum(a = 2, b = 2):
    sum = a + b
    return sum # will return sum
c = sum(4, 3) # the variable c will be equal to the return value
print(sum(5, 5)) # you can pass values as arguments to another function
The function call is slower than normal code. This isn’t noticeable unless it’s called in a loop. If you want the loop to be as fast as possible, you might want to avoid calling a function and just insert it into the body of the loop.

Optional parameters

When describing a function in Python 3, arguments that are given initial values are optional. Mandatory parameters should be described first, followed by optional ones. We do not need to specify optional parameter values when calling a function. If we want to change the value of an argument without changing the initial values of other arguments, we can refer to it by its key. Here is an example:

def example(first, second=3, third=5):
example('my string', third=4)

The output will be as follows:

my string

A function with a variable number of arguments

It is often necessary to create a function that can take a different number of arguments. This can be done by passing a list or an array, but Python allows a more convenient approach (also using a list). In order for a function to accept a variable number of arguments, the ” * “. When the programmer passes arguments, they are written to a tuple whose name matches the argument name:

def variable_len(*args):
    for x in args:
variable_len(1,2,3) # will print 1,2,3

You can use two asterisks instead of one, then the arguments will not be put into a list but into a dictionary:

def variable_len(**args):
    for x, value in args.items():
        print(x, value)
variable_len(apple = "apple", bread = "bread") 
# prints apple apple bread bread

Anonymous functions

This is a special kind of function that is declared with the keyword lambda instead of def: Lambda functions take any number of arguments, but cannot contain multiple expressions and always return only one value. In Python programming, you can get away with anonymous functions, which are essentially regular functions, but without a name and with a limit of one expression. However, using them in the right places makes it easier to write and understand the code. For example, in the calculator program we used them to make button click handlers.


The syntax of lambda functions in Python 3 provides only one expression: lambda arg1, arg2, ... argn: expression. In practice, they work like this:

x = lambda arg1, arg2: arg1 * arg2
print(x(5,5)) # prints 25
print(x(3,5)) # prints 15

Return values

You can use the return operator from a function to return one or more values. The return object can be a number, a string, or None. To return multiple values, you must write them separated by commas. Python allows you to return a list or another container from a function: simply specify the container name after the return keyword. Here’s an example of when a list is returned:

def x(n):
    a = [1,3]
    a = a * n
    return a
print(x(2)) # prints [1,3,1,3]

And this is an example of how a function in Python 3 returns multiple values. Since the variables are listed in commas, they form a list. These values can be assigned to multiple variables at once, as shown in the following example:

def example():
    language = "python"
    version = 3
    flag = True
    return language, version, flag
language, version, flag = example()
print(language, version, flag) # this will print python 3 true


A recursion is when a function calls itself. It can be used instead of loops, for example, to solve factorial problems.

def f(num):
    if num == 0:
        return 1
    return f(num-1) * num
print(f(5)) # prints the number 120

Recursion is recommended only where it is really needed. The Python interpreter automatically allocates memory for a running function, if there are too many calls to itself it will cause a stack overflow and crash. The following code will raise a “RecursionError” exception, which indicates that the maximum recursion limit has been exceeded.

def x(num):
    a = num - 1

You can find out the maximum limit and change it using getrecursionlimit() and setrecursionlimit(limit) from the sys library. One example of the use of recursion is to calculate Fibonacci numbers.

Empty function

To create an empty function, you need to use the stub operator pass in its body. Then it will exist and not do anything. Such functions can be used for various specific tasks, for example, when working with classes, asynchronous form sending.

Programmers usually make a function empty when they want to postpone its implementation for later (e.g., its algorithm has already been planned but not yet implemented, but it is necessary to execute the code to check whether the rest of the code works).

Here is an example:

def example():


The scope is an important part of any programming language. It allows you to use the same variable name several times in the same module. Scopes also make a program more secure by preventing access to important variables. There are two scopes in Python:

  • Global. Variables are declared directly inside the module and can be accessed from anywhere in the program.
  • Local. Variables are declared in the function body and are only available within the function.

It’s important to understand, from the local scope you can access variables that are in the global scope, but not vice versa.

And you can read a global variable just by accessing it. But to write, it is necessary to specify with the keyword global that it is the global variable we are working with!

Here is an example:

val1 = "my global"
val2 = "another global"
def example():
    print(val1) # print my global
    global val2
    val2 = "change another global"
print(val2) # Prints "change another global

You can read more about scopes in a separate article on the website.

The main built-in functions in Python

Python provides all basic functions needed to do this, and with add-on modules (by plugging in different libraries) you can find already implemented methods for almost any task.

  • print() Outputs objects to the screen or to a file. Example use print("output string", end=""). Accepts arguments:
    • object – the thing to be printed;
    • sep – separator between objects, by default it is a space;
    • end – ending after the object, for example the control character “n”;
    • file – attribute that allows to pass an object to a file (by default it outputs to the screen);
  • len() Returns the number of elements contained in a tuple, dictionary or list.
  • str() Converts the object passed as argument to a string.
  • int() Converts the object to an integer. Passing a string as an argument causes an error, the integer is output without change, and the fractional part of the floating-point number is discarded.
  • range() Returns a range of values, mostly used in a for loop condition.
  • bool() Causes the object to be of logical type. For example, 0 is False and 1 is True.
  • sum() Returns the sum of the passed elements.
  • min() and max() Returns the minimum and maximum element of the passed in.
  • type() Returns the type of the object, usually used when debugging code.
  • dir() Returns a list of names available in the local scope, or attributes of the object passed as an argument.
  • help() Outputs information about the passed object from the built-in help system. It should only be used interactively with the Python interpreter.

Related Posts