Functions in Python and how to use them, Examples
Table of Contents
Functions in Python:
Python provides various predefined functions. For example, len is the number of elements in a list or the number of characters in a String; print outputs the data specified in the parameters, etc. Next to it there are innumerable other functions that are defined in modules, e.g. sin or sqrt in the module math, randint or random in the module random, sleep in the module sys etc.
This section is about defining your own functions. In order you can structure your code better and more clearly. In many cases you can also avoid redundancy in the code functions.
Python offers two options for defining functions: The code for common functions, start with def. You can also use minimal Define overhead so-called lambda functions and apply them immediately.
This is particularly useful if you only want to use simple functions on one Position in your program.
Amazon Purchase Links:
*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!
Define your own functions in Python
The definition of your own functions begins with the keyword def. Follows the Function name for which the same rules apply as for variable names. The parameters must put in round brackets.
def function name (para1, para2, para3):
code
A few rules apply to programming and using functions in Python:
- Functions in Python must be defined before they can be used. Because of that it is customary to define all functions first and only afterwards to indicate the rest of the code. The code execution thus begins in the first line that does not belong to a function definition.
- Functions without parameters are permitted, but the round brackets are always required.
- Functions can be left prematurely with return. The usage of return is optional.
- With return the function can return a result. Every Python is Data type permitted, including lists, tuples, etc. In this way, a function simply return multiple values.
- Functions can be nested. So it is permissible in a function f1 to define another function f2. f2 can then only be used within used by f1, which is why the nested definition of functions rarely occurs in practice.
In the following applet first two functions are defined and this one then called to show the basic handling of functions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#! / usr / bin / python3 # Function with no result def f1 (x, y): print ('Parameter 1:', x) print ('Parameter 2:', y) # Function with result def f2 (x, y): return x + y |
Program execution begins here
1 2 3 4 5 6 7 8 9 10 11 |
f1 (2, 3) # outputs the parameters # Output: parameter 1: 2 # Parameter 2: 3 n = f2 (4, 5) print (n) # Issue: 9 |
Local and global variables
Functions can read variables that are defined outside of the function:
1 2 3 4 5 6 7 8 9 |
#! / usr / bin / python3 def f1 (): print (x) x = 3 f1 () # issue 3 |
Conversely, variables that are initialized in a function – that is, those on to the left of an assignment – as local: You can only use the Function can be used. Internally, it uses Python to store local variables a so-called namespace.
1 2 3 4 5 6 7 8 9 10 11 |
#! / usr / bin / python3 def f1 (): y = 5 print (y) # issue 5 f1 () print (y) # error, y is not defined! |
This rule also applies when a variable in a function has the same name has like a variable outside the function or in another function. In the following example there are two variables z: one within f1, the other outside. The variables are completely independent of each other and influence not yourself!
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#! / usr / bin / python3 def f1 (): z = 5 print (z) # issue 5 z = 3 f1 () print (z) # Issue 3! |
There is an error in the following applet. z is considered a local variable within the function f1. Therefore, z = z + 3 cannot work because z on the right side of the = sign is used before the variable within the function was defined.
1 2 3 4 5 6 7 8 9 10 11 |
#! / usr / bin / python3 def f1 (): z = z + 3 # error, z is not defined print (z) z = 3 f1 () |
This error also occurs if z is initialized above the function definition. The only decisive factor here is that z is a local variable within the function f1.
1 2 3 4 5 6 7 8 9 10 11 |
#! / usr / bin / python3 z = 3 def f1 (): z = z + 3 # error, z is not defined print (z) f1 () |
If you want to change a variable in a function that is outside the function has been initialized, then you can use this variable in the function as global mark. Strictly speaking you are saying that the function z is not considered to be local should consider variable, rather than a variable from global scope (Global Scope) of the program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#! / usr / bin / python3 def f1 (): global z z = z + 3 print (z) # Issue 6 z = 3 f1 () print (z) # Issue 6 |
Avoid global variables in functions!
In practice, the keyword is usually avoided globally because it is often too visible code. Instead, it is usually better to use the function result return with return and then save. The following listing gives here for an example.
1 2 3 4 5 6 7 8 9 10 11 |
#! / usr / bin / python3 def f1 (x): return x + 3 z = 3 z = f1 (z) print (z) # Issue 6 |
Python Function parameters
Parameters are used to transfer data to a function. Internally the parameters are like local variables. A parameter with the name x is thus completely independent of a variable of the same name that is outside the function
is defined:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#! / usr / bin / python3 def f1 (x): x = 6 print (x) # issue 6 x = 3 f1 (x) print (x) # issue 3 |
The same applies to the transfer of data in the parameters of a function Rules as for variable assignments. This means that in the case of immutable data types, a change in the data is excluded by the function, as the above example also proves. The situation is somewhat more complicated with variable data types, e.g. with lists or general for objects. In this case, too, a direct assignment means that the data can only be changed within the function, but not outside:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#! / usr / bin / python3 def f1 (x): x = [4, 5] print (x) # output [4, 5] x = [1, 2] f1 (x) print (x) output [1, 2] |
A change in the content of an object, a list, of a set etc., for example adding another element!
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#! / usr / bin / python3 def f1 (x): append (3) print (x) # output [1, 2, 3] x = [1, 2] f1 (x) print (x) # output [1, 2, 3] |
Optional parameters
With para = default a default value can be defined for a parameter. This Parameter is therefore also optional. All optional parameters must be on at the end of the parameter list. This makes calling functions with many optional parameters clearer the function parameters can also be transferred in the notation name = value will. The function call with named parameters also has the advantage that you don’t have to stick to the order of the parameters and the code below is more legible under certain circumstances.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#! / usr / bin / python3 def f (a, b, c = -1, d = 0): print (a, b, c, d) f (6, 7, 8, 9) # issue 6 7 8 9 f (6, 7, 8) # output 6 7 8 0 f (a = 6, b = 7, d = 9) # output 6 7 -1 9 f (d = 9, b = 7, a = 6) # output 6 7 -1 9 f (6, 7) # output 6 7 -1 0 f (6, 7, d = 3) # output 6 7 -1 3 f (6) # error, b is missing f (b = 6, c = 7) # error, a is missing |
Variable number of parameters
If you define a parameter in the form * para or ** para, this one takes Parameters against any number of values. With * para these parameters appear afterwards available as a tuple, for ** para as a dictionary. ** Must have para arguments passed as named parameters.
1 2 3 4 5 6 7 8 9 10 11 |
#! / usr / bin / python3 def f (a, b, * c): print (a, b, c) f (1, 2, 3) # output 1 2 (3,) f (1, 2, 3, 4) # output 1 2 (3, 4) f (1, 2, 3, 4, 5, 6) # output 1 2 (3, 4, 5, 6) |
If the data you want to pass to a function is in a list, a Tuples or another enumerable data structure is present when the function is called function (* list) is also allowed. With that the elements automatically distributed to the parameters in the list:
1 2 3 4 5 6 7 8 9 |
#! / usr / bin / python3 def f (a, b, * c): print (a, b, c) l = [1, 2, 3, 4, 5, 6] f (* l) # output 1 2 (3, 4, 5, 6) |
You can use the notation * list in the parameters of every function, e.g. also in print:
1 2 3 4 5 |
l = [1, 2, 3] print (l) # print the whole list, so [1, 2, 3] print (* l) # List elements become parameters, output 1 2 3 |
In combination with List Comprehension, expressions can result which refer to look strange at first glance. In the following example, [x * x for …] Squares of all list items. * causes the results to be used as a print parameter will:
1 2 3 4 5 |
#! / usr / bin / python3 l = [1, 2, 3] print (* [x * x for x in l]) # output 1 4 9 |
Within the function, you can use len (c) to determine how many parameters are transferred were. The following example demonstrates the handling of a ** parameter:
1 2 3 4 5 6 7 8 9 |
#! / usr / bin / python3 def f (a, b, ** c): print (a, b, c) f (1, 2) # output 1 2 {} f (1, 2, x = 4, y = 7) # output 1 2 {'y': 7, 'x': 4} |
Named parameters can also be taken from a dictionary with the notation ** dict transferred to the parameter list:
1 2 3 4 5 6 7 8 9 |
#! / usr / bin / python3 def f (a, b, ** c): print (a, b, c) dict = {'a': 1, 'b': 2, 'x': 3, 'y': 4, 'z': 5} f (** dict) # output 1 2 {'y': 4, 'x': 3, 'z': 5} |
There may be a maximum of one * or ** parameter in the parameter list. A ** – No further parameters may follow parameters. With * parameters there are more simple parameters allowed. But these must always be named like that the following example shows:
1 2 3 4 5 6 7 8 9 |
#! / usr / bin / python3 def f (a, b, * c, x): print (a, b, c, x) f (1, 2, x = 3) # output 1 2 () 3 f (1, 2, 3, 4, x = 5) # output 1 2 (3, 4) 5 |
Lambda functions in Python
You often use your own functions for two reasons: on the one hand, to break down the complex code into manageable pieces, or else because you have a specific Want to do tasks in different places in the code and so to avoid redundancy in the code. But sometimes there is a third variant: You need at one point in the code e.g. in map, filter or to formulate a simple Callback function – an often quite simple function.
The conventional way is then quite cumbersome: You have to explicitly define a function that is often only one-line with def and then only use it once. Lambda functions in python are a space-saving alternative for such cases: These are python functions that are defined ad hoc and at the same time on this Position in the code can also be used immediately. For this reason there is none Need to give the function a name, which is why Lambda functions correctly referred to as anonymous functions. You could also be a little more casual speak of “throw-away functions” which are only defined for one-time use will.
The following line shows the syntax for defining a Lambda function in python. There is a limitation of Lambda functions compared to other functions Incidentally, lambda functions only consist of a single expression allowed to!
lambda var1, var2, var3, …: expression
The following mini-program shows the use of two lambda functions: The first lambda expression recognizes numbers divisible by 3 and uses this criterion to accommodate the elements in l2. The second lambda expression will apply to all Elements of l2 are applied to divide them by 3 as an integer. The resulting List lands in l3:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#! / usr / bin / python3 l1 = [1, 2, 3, 9, 345, 36, 33] # l2 contains all elements of l1 that are divisible by 3 l2 = list (filter (lambda x: x% 3 == 0, l1)) print (l2) # output [3, 9, 345, 36, 33] # divide all elements of l2 by 3 l3 = list (map (lambda x: x // 3, l2)) print (l3) # output [1, 3, 115, 12, 11] |
It is unusual, but syntactically permissible, to assign a lambda function to a variable. This variable can then be used like an ordinary function. The two functions f1 and f2 in the following code are therefore equivalent:
1 2 3 4 5 6 7 8 9 10 11 |
#! / usr / bin / python3 def f1 (x, y): return (x + 1) * (y + 1) f2 = lambda x, y: (x +1) * (y +1) print (f1 (2, 3)) # issue 12 print (f2 (2, 3)) # Issue 12 |
Python Functional programming
Python can handle functions extremely flexibly. The previous example has already demonstrated that you can use functions such as numbers, lists or objects easily can store in a variable – to this variable then like a function to use.
Functions themselves can also pass the parameters of another function. Functions can also return a function as a result hand back. Consider the following example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#! / usr / bin / python3 import math def funcbuilder (f, n): def newfunc (x): return f (n * x) return newfunc # forms the function sin (2 * x) f1 = funcbuilder (math .sin, 2) print (f1 (0.4), math. sin (0.4 * 2)) # Edition 0.7173560908995228 0.7173560908995228 # forms the function cos (4 * x) f2 = funcbuilder (math .cos, 4) print (f2 (0.07), math. cos (0.07 * 4)) # Edition 0.9610554383107709 0.9610554383107709 |
funcbuilder expects a function and a number as parameters. This becomes the new Function new (x) = f (n * x) formed. return returns the function. The remaining lines show the application of funcbuilder.
If you are using a lambda expression in funcbuilder, you can use the code further shorten. There are only a few programming languages that have such constructs support so elegantly.
def funcbuilder (f, n):
return lambda x: f (n * x)
The next example follows a similar idea, but does not provide a function, but a result right away. The function expects three parameters: f, g and x. Here f and g must be functions. The result is f (g (x)).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#! / usr / bin / python3 import math nest def (f, g, x): return f (g (x)) nest (print, math .sin, 0.2) # 0.19866933079506122 print (math .sin (0.2)) # 0.19866933079506122 result = nest (math .sin, math .sqrt, 0.5) print (result == math .sin (math. sqrt (0.5))) # True |
Opinions can be divided about the practical use of these gimmicks. Mathematically trained programmers, in particular, will enjoy them. Many mathematical concepts are easier to implement in Python than in other Programming languages.