In programming languages, functions are a named piece of code. These are separate blocks in the text of the program. They are defined using the reserved word def. In Python, functions can be called 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. Functions allow you to reuse a piece of code without rewriting it.
This is the simplest way to package the execution logic of individual parts of a program. This reduces the volume and time that a specialist spends on creating a script.
How to write the first function
Python 3 has the simplest print() function for beginners in programming. To see it in action, you need a development environment. To do this, download the language distribution from the official website and install Python on your computer.
Open the start menu and inFind Python 3 in the list of programs. Left-click to expand it. In the list that opens, find the IDLE environment and run it. Type print("Hello, World!") and hit 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 type python.exe. A normal interpreter will open, 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 efficient as the builtin print() or open() but are different 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 execute it.
The def statement creates a new object and gives it a name. That is, when the interpreter starts to implement, it creates a new object and binds it to the name specified after def. To store data, various attributes can be attached to functions.
Now let's write a function that returns the phrase "Hello, World!" using only def:
- >>> def hello_world():
- print("Hello, World!")
- >>> hello_world() function call
- Hello, World!
Function syntax and return
A def statement in Python consists of a header and is written as follows:
>>>def (argument 1, argument 2, argument N):
The heading is followed by a block of instructions that begins with a mandatory indent. In IDLE, the interpreter will do it automatically. But in notepad or another text editor, you might forget to press Tab. Then the function will not run. The code in a statement block is called the body of the function and is executed every time it is called.
Also, the body sometimes contains return:
- def (argument 1, argument 2, argument N):
Return ends the function and passes the result object to the caller. The instruction is optional. The function will run without a return, and will end when the flow of control reaches the end of its body.
Parameters and arguments
You can pass parameters to each function, which are specified in brackets after def. In Python, they are written as comma-separated variables. Values or object references to these names are assigned in a block followed by a colon. After the assignment operation, it is customary to call them arguments, not parameters.
Arguments inside a function have nothing to do with objects outside it, so in programming they are referred to as local variables. The scope is limited to a function block that starts with def and ends with return. To make it clearer, here is an example:
- x=12 assign references to integer objects to variables
- >>>def example(x, y): create a function named example
- x="Hello" assign values to arguments x, y
- print(x, y, sep=", ")
- return None
- >>>example(x, y) call the function without forgetting 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 x and y from the global scope.
Argument values do not have to be specified inside the function, you can enter them manually when calling it:
- >>>def E_2(x, y):
- return x + y
- >>>E_2("Hello, " "Python!") to separate words, put a space before the closing quote
- Hello, Python!
- E_2(5, 4)
As you can see from the simple function E_2 example, the result depends entirely on the type of the x and y objects. In the first case, E_2 performed the concatenation, and in the second, the arithmetic addition operation. This is the principle of polymorphism and dynamic typing. The fact that objects define syntactic meaning makes the language flexible and simple. No need to waste time separately specifying the data type that the function works with.
This rule concerns working with variables in different scopes. By default, all names you create in the body of a function are considered local. And the names in the module are global. If desired, names can be assigned the value of top-level variablesusing notlocal and global.
The LEGB rule explains the name resolution scheme:
- As soon as the interpreter finds a variable inside a def statement, it first looks for values in the local scope.
- If the search fails, it jumps to the scope of any overarching statement def.
- The interpreter then moves on to the global names at the top level of the module and those labeled as global.
- If the search fails, the interpreter looks for names in Python's built-in scope.
Let's consider an illustrative example:
- >>>def example_2(K):
- C=L + K+R
- return C
Variables L and R are at the top level and are global names. R, C, and K are local variables, since the value assignment takes place inside the def.
The interpreter first performs the addition operation on the local R, C, and K, ignoring the variable R outside the def statement. Then it looks for L, and not finding it among the local names, goes to the top level.
What is lambda
Besides def, Python functions can be created using special expressions, one of which is lambda. It got its original name in honor of the lambda calculus of the LISP language.
Like def, lambda creates a function that can be called later, but does not associate it with any name. On practicelambda is used when you need to delay the execution of a piece of code.
Basics of lambda expressions
Lambda expressions look like def statements. First, the keyword lambda is written, then the arguments, a colon and the expression itself:
- >>>f=lambda x, y, z: x + y + z
- >>>f(2, 3, 4)
The body of a lambda is a single expression, not a block of statements. Due to this, lambda is limited in its capabilities and not as versatile as def. Only logic can be implemented in it, without while or for loops.
For a lambda, the rules for finding variables are similar to those for def. Names specified outside the expression are global, inside they 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, def. is enough for beginners to get started.