Python Programming

Functions in Python and how to use them, Examples

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:

Top Gaming Computers

Best Laptops

Best Graphic Cards

Portable Hard Drives

Best Keyboards

Best High Quality PC Mic

Computer Accessories

*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):


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:

Program execution begins here

Local and global variables

Functions can read variables that are defined outside of the function:

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.

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!

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.

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.

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.

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.

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:

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:

A change in the content of an object, a list, of a set etc., for example adding another element!

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.

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.

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:

You can use the notation * list in the parameters of every function, e.g. also in print:

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:

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:

Named parameters can also be taken from a dictionary with the notation ** dict transferred to the parameter list:

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:

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:

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:

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:

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)).

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.

Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button