In programming languages, functions are the named part of the code. These are separate blocks in the program text. Defined using the reserved word def. In Python, functions can be accessed an unlimited number of times from any part of the script.
Why functions are needed
Functions are an indispensable tool for a programmer. With their help, the developer structures the program, making it clearer and more compact. With the help of functions, it is possible to reuse a separate part of the code without writing it again.
This is the easiest way to package the logic of the execution of individual parts of the program. This reduces the amount and time that a specialist spends on creating a script.
How to write the first function
In Python 3, for beginners, their familiarity with programming is the simplest print () function. To see it in action, you will need a development environment. To do this, download the language distribution from the official site and install Python on your computer.
Open the Start menu and find Python 3 in the list of programs. Expand it by left-clicking. In the list that opens, find the IDLE environment and run it. Type print ("Hello, World!") And press Enter. The interpreter will return the result of your first function.
Some programmers prefer to work in the console. If you are one of them, press win + R and enter the python.exe command. A regular interpreter opens, only with the cmd interface. Type the program as described above and press Enter at the end to see the result.
How to use def
New functions are created using the def statement. They are just as effective as the built-in print () or open (), but differ from functions in compiling languages. Python def refers to executable instructions. This means that the function does not exist until the interpreter sees it and proceeds to its execution.
The def statement creates a new object and gives it a name. That is, when the interpreter begins implementation, it creates a new object and associates it with the name specified after def. To store data to functions, various attributes can be attached.
Now let's write a function that returns the phrase βHello, World!β, Only using def:
- >>> def hello_mir ():
- print ("Hello, World!")
- >>> hello world () # function call
- Hello World!
Function Syntax and return
A Python def statement consists of a header and is written according to the following rules:
- >>> def <name> (argument 1, argument 2, argument N):
After the header is a block of instructions, which begins with a mandatory indent. In IDLE, the interpreter will do it automatically. But in notepad or another text editor, you may forget to press Tab. Then the function will not start. The program code in the instruction block is called the body of the function and is executed every time it is called.
Also in the body is sometimes return:
- def <name> (argument 1, argument 2, argument N):
- ...
- return <value>
Return terminates the function and passes the result object to the calling program. The instruction is not binding. The function will work without return, and will end when the control flow reaches the end of its body.
Parameters and Arguments
Each function can be passed parameters that are indicated in brackets after def. In Python, they are written as comma-separated variables. Values ββor object references to these names are assigned in the block after the colon. After the assignment operation, they are usually called arguments, not parameters.
Arguments inside a function are in no way connected with objects outside it; therefore, in programming, they are referred to as local variables. The scope is limited to a function block that begins with def and ends with return. To make it clearer, we give an example:
- x = 12 # assign variable references to integer objects
- y = 34
- >>> def example (x, y): # create a function called example
- x = "Hello" # assign values ββto the arguments x, y
- y = "Python"
- print (x, y, sep = ",")
- return none
- >>> example (x, y) # call the function, do not forget to specify the parameters
- Hello Python
- >>> print (x, y)
- 12 34
Pay attention to the penultimate line of code. In the Python interpreter, the print () command returned the x and y variables from the global scope.
The values ββof the arguments do not have to be specified inside the function, you can enter them manually when you call it:
- >>> def E_2 (x, y):
- return x + y
- >>> E_2 (βHello,β βPython!β) ββ# So that the words are separated, put a space before the closing quote
- Hello Python!
- E_2 (5, 4)
- 10
As can be seen from the example with the simple function E_2, the result completely depends on the type of objects x and y. In the first case, E_2 performed concatenation, and in the second, the arithmetic addition operation. This is the principle of polymorphism and dynamic typing. The fact that objects define the syntactic meaning determines the flexibility and simplicity of the language. There is no need to waste time separately specifying the type of data with which the function works.
LEGB rule
This rule applies to working with variables in different scopes. By default, all names that you create in the function body are considered local. And the names in the module are global. If desired, names can be assigned the value of top-level variables using the notlocal and global instructions.
The LEGB rule explains the name resolution scheme:
- As soon as the interpreter finds the variable inside the def statement, it first searches for values ββin the local scope.
- If the search fails, it moves to the scope of any comprehensive def statement.
- Further, the interpreter moves to global names at the top level of the module and those designated as global.
- If the search returns no results, the interpreter searches for names in the Python built-in scope.
Consider a good example:
- >>> L = 85
- >>> R = 23
- >>> def example_2 (K):
- R = 10
- C = L + K + R
- return C
- >>> example_2 (5)
- 100
Variables L and R are at the top level and are global names. R, C, and K are local variables since value assignment takes place inside the def statement.
The interpreter first performs the addition operation for local R, C, and K, ignoring the variable R outside the def statement. Then it searches for L, and not finding it among the local names, it goes to the upper level.
What is lambda
In addition to def, in Python you can create functions using special expressions, one of which is lambda. It got its original name in honor of the lambda calculi of the LISP language.
Like def, lambda creates a function that can be called later, but does not bind it to any name. In practice, lambda is used when you need to delay the execution of a piece of code.
The basics of lambda expressions
In appearance, lambda expressions resemble def instructions. The lambda keyword is written first, then the arguments, the colon, and the expression itself:
- >>> f = lambda x, y, z: x + y + z
- >>> f (2, 3, 4)
- 9
The body of a lambda is one single expression, not a block of instructions. Due to this, lambda is limited in capabilities and not as universal as def. Only logic can be implemented in it, without while or for loops.
For lambda, the rules for searching for variables similar to def apply. Names specified outside the expression are global, inside are local, and they do not affect each other in any way.
Lambda expressions are very convenient to embed in a program. Due to their small size, they minimize and simplify the code. But the use of lambda is not fundamental. In Python 3, a def statement will suffice for beginners.