English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this article, you will learn about functions, what functions are, the syntax of functions, their composition, and types. In addition, you will also learn how to create functions in Python.
In Python, a function is a group of related statements that perform a specific task.
Functions help to decompose our program into smaller modules. As our project grows larger, functions make it more organized and easier to manage.
In addition, it avoids rewriting the same code repeatedly, making the code reusable.
def function_name(parameters): """docstring""" statement(s)
The display above shows the function definition composed of the following components.
The 'def' keyword marks the beginning of a function header.
Used to uniquely identify the function. Function naming followsWriting identifiers in Pythonthe sameRules.
Used to pass values to the function's parameters. They are optional.
The colon (:) marks the end of the function header.
Optional documentation string (docstring), used to describe the function.
One or more valid Python statements that make up the function body. The statements must have the same indentation level (usually4a space).
Optional return statement, used to return a value from the function.
def greet(name): "" This is a greeting function Passed through the name parameter The name of the person to greet "" print("Hello, " + name + ". Good morning!")
After defining a function, we can call it from another function, program, or even the Python prompt. To call a function, we just need to type the function name with the appropriate parameters.
>>> greet('Paul') Hello, Paul. Good morning!
Note:Try running the above code in a Python program with a function definition to view the output.
def greet(name): "" This is a greeting function Passed through the name parameter The name of the person to greet "" print("Hello, " + name + ". Good morning!") greet('Paul')
The first string after the function header is called a docstring, which is an abbreviation for documentation string. It briefly describes the function's purpose.
Although it is optional, documentation is a good programming habit. Be sure to comment your code unless you remember the time and what you ate for dinner last year today.
In the above example, we have a documentation string just below the function header. We usually use triple quotes to extend the documentation string to multiple lines. This string can be used as the __doc__ attribute for us.
For example:
Try running the following content in the Python shell to view the output.
>>> print(greet.__doc__) This is a greeting function Passed through the name parameter The name of the person to greet
For more information about Python documentation strings, please visitPython Docstrings.
The return statement is used to exit the function and return to the calling function's location.
return [expression_list]
The statement can contain an expression, which will be evaluated and return a value. If there is no expression in the statement, or the return statement itself does not exist in the function, the function will return the None object.
For example:
>>> print(greet("May")) Hello, May. Good morning! None
None is the return value because the greet() function prints the name directly and does not use the return statement.
def absolute_value(num): """This function returns the absolute value of the input number""" if num >= 0: return num else: return -num print(absolute_value(2)) print(absolute_value(-4))
Output result
2 4
The scope of a variable is the part of the program where the variable can be recognized. Parameters and variables defined inside the function cannot be seen from outside the function. Therefore, they have local scope.
The lifecycle of a variable is the time when the variable exits the memory. The lifecycle of a variable inside the function is as long as the time the function is executed.
Once we return from the function, they will be destroyed. Therefore, the function cannot remember the variable values of its previous calls.
This is an example to illustrate the lifecycle of variables inside the function.
def my_func(): x = 10 print("Function internal value:",x) x = 20 my_func() print("Function external value:",x)
Output result
Function internal value: 10 Function external value: 20
Here, we can seexThe initial value is20. Even if the function my_func() setsxChange the value to10,it will not affect the value outside the function.
This is because the variable inside the functionx withThe x variable outside the function is different. Although they have the same name,But they are two different variables with different scopes.
On the other hand, variables outside the function can be seen from the outside. They have global scope, which means that the global variable can be used inside and outside the function.
We can read these values from inside the function, but we cannot change (write) them. If we want to change the value of a variable outside the function, we must use the keyword global and declare them as global variables.
基本上,我们可以将函数分为以下两种类型: