Functions and methods in Python

 

Source code better organize functions and methods in Python

Functions can be used to summarize parts of a program in Python. This serves to better structure the code and saves the outsourcing developer redundant work.

Companies on the topic

Definition of an own example function, which can be called again within the program code.Definition of an own example function, which can be called again within the program code.

(Image: Joos / Microsoft)

If certain functionalities are regularly required in different places in a program, it makes sense to summarize them in one function. Whenever the functionality is needed, it is sufficient to call the respective function in the program.

At the same time, the program code becomes much clearer, because associated code is summarized in the program. With this increasing overview, the sources of errors also decrease, since an error-free function is error-free at all points in the code and is called at any time.

If developers instead implement the tasks on each code area without a function, the number of possible sources of error increases, while the overview decreases. In other words, functions are simply subroutines of a program. In addition to the possibility to create own functions, functions are also integrated in Python that help with tasks. The built-in functions are also called “built-in Functions”.

Call functions

The built-in functions and the self-created functions are called by calling the name of the function in the code and then the corresponding parameters in parentheses. This is a function call. An example is the use of the function print.

Show help on functions.Show help on functions.

(Image: Joos / Microsoft)

With print (“Hello“) “Hello” is also displayed in the console. To display a help to print, in this example you can use help(print) be worked. The help command also works with other functions, such as help(max). function max displays the highest value from a list of values:

Use functions and output results with theUse functions and output results with the “print” function.

(Image: Joos / Microsoft)

zahl = max([1,4,10])
print(zahl)

The list of the example above with max is a parameter of the function. If a function results in a result, as in the example above, the value “10” for the variable “number”, the value can be used as an instance in the program

Create your own functions with “def”

If own functions are created, they must correspond to the specifications that also apply to built-in fuctions. A function must be given a name by which it can be started with a function call from within the code. Then it must be specified how data from the program code can be transferred to the function.

Finally, it is necessary to define which value the function returns. If no value is set, such as the highest value in a list above max, then the function returns “none” as a result.

Own functions can be created with the keyword def create. For example, you can define a simple function that outputs the text “This is a text from a function” as follows:

def meinefunktion():

print(„Das ist ein Text aus einer Funktion“)

print(„Programm-Ende“)

In order to test the procedure, it is specified in parallel that the text “End of program” is output. If the program is started, only the string “Program end”appears in this example. This is because the function has only been defined and the program continues with the actual code.

Conversely, this means that the function is only executed and displays the text when a function call is explicitly made:

def meinefunktion():
print(„Das ist ein Text aus einer Funktion“)
meinefunktion()
print(„Programm-Ende“)

Create your own example.Create your own example.

(Image: Joos / Microsoft)

In this example before print (“Program end”), we call the previously created function via” myfunction ()”. Since the function does nothing else than the text “This is a text from a function”, in this case the two lines of text appear:

Das ist ein Text aus einer Funktion
Programm-Ende

Calling your own functions in the code

The advantage of functions is the possibility to call them at any point in the code and to use your program code without having to type everything again. In this example, the function is called multiple times in different places and always outputs its defined result:

Multiple calling of a function.Multiple calling of a function.

(Image: Joos / Microsoft)

def meinefunktion():
print(„Das ist ein Text aus einer Funktion“)
meinefunktion()
meinefunktion()
meinefunktion()
print(„Programm-Ende“)
meinefunktion()

An important purpose of functions is to obtain values from the program code, process them and then pass them back to the program. In the following example, the value “10” is passed to the function “halving”. The function halves the passed value and outputs it:

def halbierung(wert1):
print("Halbierung")
print(wert1/2)
halbierung(10)
print(„Programm-Ende“)

Passing values to a function.Passing values to a function.

(Image: Joos / Microsoft)

By calling the function “halving” and passing the value “10”, the function processes the passed value as” value”, performs the calculation and outputs the result. After that, the program continues and reports the “program end”. Functions can also be nested. It is also possible to call one or more functions in functions again.

Using methods

Methods are functions that can be applied depending on specific data types and instances. With the data type “List”, for example, the method” sort ” can be used to sort a list. A method refers to an instance.

Sort a list using the sort method.Sort a list using the sort method.

(Image: Joos / Microsoft)

For example, in this example, if a list (or one-dimensional array) of numbers is stored as a variable with numbers = [1,5,3,2,10,7,6] and this list of numbers.sort (), the instance of this action is a sorted order in the form [1,2,3,5,6,5,10]. The instance can be reused in the code. Which methods are available depends on the data type used.

Methods generally work like functions and can treat variables as objects. In the following example, a text of a variable is saved (text) then a new variable is defined (text new) and the lower method converts the variable “text new” as lowercase letters and then outputs it with the print function:

Working with methods.Working with methods.

(Image: Joos / Microsoft)

text = "Das iST eIn BeISpIEL"
textneu = text.lower()
print(textneu)

The output would be:

das ist ein beispiel

Use methods to edit variables without changing the variable.Use methods to edit variables without changing the variable.

(Image: Joos / Microsoft)

Methods thus offer an object-oriented view of instances, variables, and other areas of programming. The good thing about such a procedure is that the original value of a variable is not changed. Both the manipulated and the original value can be output via the print function:

text = "Das iST eIn BeISpIEL"
print(text.lower())
print(text)

(ID:47135449)

Ready to see us in action:

More To Explore

IWanta.tech
Logo
Enable registration in settings - general
Have any project in mind?

Contact us:

small_c_popup.png