Certain program parts or partial problems of a program can be grouped into functions (also referred to as "procedures" or "subprograms"). This program part, this so-called function, can now be used (called) as often as needed in the program.

For example, a program logon can be grouped to a function and called again after 10 minutes of inactivity or if the password is wrong.

Principle of the function call


Call of a function

Call and return of a function


Example

The following function calculates the quotient of numerator and denominator.

def div(numerator, denominator): # define the function with the name div with two parameters
    return numerator/denominator # return the result of the division

This is how the above function can be called.

x = div(1, 2)        # a first call: return value is assigned to x                  

print(div(2, 3))     # another call: return value is printed

Any number of values can be passed to a function as parameters. 

In Python - unlike in other programming languages - multiple values can also be returned:

def func():
    return 1,2

a,b = func() print(a,b) # output: 1 2

In this example, the output is as follows:
1 2


Advantages

Code parts are not copied several times with Copy and Paste, only because they are used several times, but code is grouped together in a function and can be called as often as desired.
  •  Code is shorter and therefore clearer.
  •  Changes only have to be made in one place.
Last modified: Thursday, 30 May 2024, 6:21 PM