Author: Han Xinzi@ShowMeAI
Tutorial address: http://www.showmeai.tech/tuto...
Article address: http://www.showmeai.tech/article-detail/81
Notice: All Rights Reserved. Please contact the platform and the author for reprint and indicate the source
1.Python function
Functions are organized, reusable snippets of code used to implement a single, or associated function.
Function can improve the modularity of application and the reuse rate of code. You already know that Python provides many built-in functions, such as print(). But you can also create your own functions, which are called user-defined functions.
2. Define a function
You can define a function that you want. Here are the simple rules:
- The function code block starts with the def keyword, followed by the function identifier name and parentheses ().
- Any incoming parameters and arguments must be placed between parentheses, which can be used to define parameters.
- The first line of the function can optionally use a document string - used to store the function description.
- The function content starts with a colon: and is indented.
- Return [expression] ends the function and selectively returns a value to the caller. A return without an expression is equivalent to returning None.
(1) Grammar
Python defines functions using the def keyword. The general format is as follows:
def Function name (parameter list): Function body
By default, parameter values and parameter names match in the order defined in the function declaration. The following is the sample code (the code can be found in Online Python 3 environment Running in:
Let's use the function to output "Hello World!":
def hello() : print("Hello World!") hello()
For the application of more complex points, the function takes parameter variables:
def my_max(a, b): if a > b: return a else: return b a = 4 b = 5 print(my_max(a, b))
Output results of the above examples:
5
Calculate the area function. The following is the example code (the code can be found in Online Python 3 environment Running in:
# Calculate area function def cal_area(width, height): return width * height def my_welcome(name): print("Welcome", name) my_welcome("ShowMeAI") w = 4 h = 5 print("width =", w, " height =", h, " area =", cal_area(w, h))
Output results of the above examples:
Welcome ShowMeAI width = 4 height = 5 area = 20
3. Function call
Define a function: give the function a name, specify the parameters contained in the function, and the code block structure.
After the basic structure of this function is completed, you can execute it through another function call or directly from the Python command prompt.
The following code calls print_myself() function:
# Define function def print_myself( str ): # Print any incoming strings print (str) return # Call function print_myself("Call user-defined function!") print_myself("Call the same function again")
Output results of the above examples:
Call user-defined function! Call the same function again
4. Parameter transfer
In python, the type belongs to the object, and the variable has no type:
a=[1,2,3] a="ShowMeAI"
It can refer to more than one type of object, and "show,3" can refer to only one type of object, while "show,3" can refer to only one type of object.
(1) Mutable and immutable objects
In python, strings, tuples, and numbers are immutable objects, while list,dict, and so on are modifiable objects.
- Immutable type: the variable is assigned a=10 and then a=5. Here, in fact, an int value object 5 is newly generated, and then a points to it, while 10 is discarded. Instead of changing the value of a, it is equivalent to newly generating a.
- Variable type: if the variable is assigned l=[1,2,3,4] and then assigned l[2]=5, the value of the third element of list l is changed. L itself does not move, but some of its internal values are modified.
Parameter passing of python function:
- Immutable type: value transfer similar to C + +, such as integer, string and tuple. For example, func(a) only passes the value of a without affecting the object itself. If the value of a is modified inside func(a), a new object of a is generated.
- Variable type: reference passing similar to C + +, such as list and dictionary. If func(l) is used, then l will be passed in. After modification, l outside func will also be affected
Everything in python is an object. Strictly speaking, we can't say value passing or reference passing. We should say passing immutable objects and variable objects.
(2) python passes immutable object instances
Check the memory address change through the id() function:
def my_change(a): print(id(a)) # It points to the same object a=10 print(id(a)) # A new object a=5 print(id(a)) my_change(a)
The output result of the above example is:
9788736 9788736 9788896
It can be seen that before and after calling the function, the formal parameter and the actual parameter point to the same object (the object id is the same). After modifying the formal parameter inside the function, the formal parameter points to a different id.
(3) Pass variable object instance
If the variable object modifies the parameters in the function, the original parameters are also changed in the function calling the function. The following is the sample code (the code can be found in Online Python 3 environment Running in:
def change_list( mylist ): "Modify incoming list" mylist.append([1,2,3,4]) print ("Value in function: ", mylist) return # Call the changeme function mylist = [10,20,30] change_list( mylist ) print ("Value outside function: ", mylist)
The object passing in the function and the object adding new content at the end use the same reference. Therefore, the output results are as follows:
Value in function: [10, 20, 30, [1, 2, 3, 4]] Value outside function: [10, 20, 30, [1, 2, 3, 4]]
5. Parameters
The following are the formal parameter types that can be used when calling a function:
- Required parameters
- Keyword parameters
- Default parameters
- Indefinite length parameter
(1) Required parameters
Required parameters must be passed into the function in the correct order. The number of calls must be the same as that declared.
Call print_ For myself() function, you must pass in a parameter, otherwise there will be a syntax error:
def print_myself( str ): "Print any incoming strings" print(str) return # Call print_ The myself function will report an error without parameters print_myself()
Output results of the above examples:
Traceback (most recent call last): File "test.py", line 10, in <module> print_myself() TypeError: print_myself() missing 1 required positional argument: 'str'
(2) Keyword parameters
Keyword parameters are closely related to function calls. Function calls use keyword parameters to determine the value of incoming parameters.
Using keyword parameters allows the order of parameters when calling a function to be inconsistent with that when declared, because the Python interpreter can match parameter values with parameter names.
The following example is in the function print_ Use parameter name when calling myself():
def print_myself( str ): "Print any incoming strings" print(str) return #Call print_myself function print_myself( str = "ShowMeAI Knowledge community")
Output results of the above examples:
ShowMeAI Knowledge community
The following example code( Online Python 3 environment )It is demonstrated in that the use of function parameters does not need to use the specified order:
def print_info( name, age ): "Print any incoming strings" print ("name: ", name) print ("Age: ", age) return #Call print_info function print_info( age=30, name="ShowMeAI" )
Output results of the above examples:
name: ShowMeAI Age: 30
(3) Default parameters
When calling a function, if no parameters are passed, the default parameters are used. Following code( Online Python 3 environment )If no age parameter is passed in, the default value is used:
def print_info( name, age = 35 ): "Print any incoming strings" print ("name: ", name) print ("Age: ", age) return #Call print_info function print_info( age=30, name="ShowMeAI" ) print("------------------------") print_info( name="ShowMeAI" )
Output results of the above examples:
name: ShowMeAI Age: 30 ------------------------ name: ShowMeAI Age: 35
(4) Indefinite length parameter
You may need a function that can handle more parameters than you originally declared. These parameters are called variable length parameters. Unlike the above two parameters, they are not named when declared. The basic syntax is as follows:
def function_name([formal_args,] *var_args_tuple ): "function_Document string" function_suite return [expression]
Parameters marked with an asterisk * will be imported in the form of tuples to store all unnamed variable parameters.
def print_info( arg1, *vartuple ): "Print any incoming parameters" print("output: ") print(arg1) print(vartuple) # Call print_info function print_info( 100, 90, 80 )
Output results of the above examples:
output: 100 (90, 80)
If no parameters are specified in the function call, it is an empty tuple. We can also not pass unnamed variables to the function. The following code( Online Python 3 environment):
def print_info( arg1, *vartuple ): "Print any incoming parameters" print("output: ") print(arg1) for var in vartuple: print (var) return # Call printinfo function print_info( 100 ) print_info( 90, 80, 70 )
Output results of the above examples:
output: 100 output: 90 80 70
Another is the parameter with two asterisks * *. The basic syntax is as follows:
def function_name([formal_args,] **var_args_dict ): "function_Document string" function_suite return [expression]
Parameters with two asterisks * * will be imported in the form of dictionary.
def print_info( arg1, **vardict ): "Print any incoming parameters" print("output: ") print(arg1) print(vardict) # Call print_info function print_info(1, a=2,b=3)
Output results of the above examples:
output: 1 {'a': 2, 'b': 3}
When declaring a function, the asterisk * in the parameter can appear separately, for example:
def f(a,b,*,c): return a+b+c
If the parameter after the asterisk * appears separately, it must be passed in by keyword.
def f(a,b,*,c): return a+b+c f(1,2,c=3) # normal f(1,2,3) # report errors
6. Anonymous function
python uses lambda to create anonymous functions.
The so-called anonymity means that a function is no longer defined in the standard form of def statement.
- lambda is just an expression, and the function body is much simpler than def.
- The body of a lambda is an expression, not a code block. Only limited logic can be encapsulated in lambda expressions.
- lambda functions have their own namespace and cannot access parameters outside their own parameter list or in the global namespace.
- Although lambda function can only write one line, it is not equivalent to C or C + + inline function. The purpose of the latter is to call small functions without occupying stack memory, so as to increase operation efficiency.
(1) Grammar
The syntax of lambda function contains only one statement, as follows:
lambda [arg1 [,arg2,.....argn]]:expression
Examples are as follows:
my_sum = lambda arg1, arg2: arg1 + arg2 # Call my_sum function print ("The added value is : ", my_sum( 10, 20 )) print ("The added value is : ", my_sum( 20, 20 ))
Output results of the above examples:
The added value is : 30 The added value is : 40
7.return statement
The return [expression] statement is used to exit a function and optionally return an expression to the caller. Return statements without parameter values return None. The previous examples do not demonstrate how to return a value. The following examples demonstrate the use of the return statement:
def my_sum( arg1, arg2 ): # Returns the sum of two parameters " total = arg1 + arg2 print("Within function : ", total) return total # Call sum function total = my_sum( 10, 20 ) print("Out of function : ", total)
Output results of the above examples:
Within function : 30 Out of function : 30
8. Forced position parameters
Python3.8 + added a function parameter Syntax / used to indicate that the function parameter must use the specified location parameter instead of the form of keyword parameter.
In the following example, parameters a and b must use the specified location parameter, c or d can be location parameter or keyword parameter, and e and f are required to be keyword parameters:
def f(a, b, /, c, d, *, e, f): print(a, b, c, d, e, f)
The following usage is correct:
f(10, 20, 30, d=40, e=50, f=60)
The following methods can cause errors:
f(10, b=20, c=30, d=40, e=50, f=60) # b cannot use the form of keyword parameter f(10, 20, 30, 40, 50, f=60) # e must be in the form of keyword parameters
9. Video tutorial
Please click to station B to view the version of [bilingual subtitles]
https://www.bilibili.com/vide...
Data and code download
The code for this tutorial series can be found in github corresponding to ShowMeAI Download in, you can run in the local python environment. Babies who can surf the Internet scientifically can also directly use Google lab to run and learn through interactive operation!
The Python quick look-up table involved in this tutorial series can be downloaded and obtained at the following address:
Extended references
ShowMeAI related articles recommended
- Introduction to python
- python installation and environment configuration
- python basic syntax
- python basic data type
- python operator
- python conditional control and if statement
- python loop statement
- python while loop
- python for loop
- python break statement
- python continue statement
- python pass statement
- python string and operation
- python list
- python tuple
- python dictionary
- python collection
- python function
- python iterators and generators
- python data structure
- python module
- python file reading and writing
- python file and directory operation
- python error and exception handling
- python object oriented programming
- python namespace and scope
- python time and date
ShowMeAI series tutorial recommendations
- Illustrated Python Programming: a series of tutorials from getting started to mastering
- Graphic data analysis: a series of tutorials from introduction to mastery
- Fundamentals of graphic AI Mathematics: a series of tutorials from introduction to mastery
- Illustrated big data technology: a series of tutorials from introduction to mastery