1, function introduction
Please see the following code:
1 | print(" _ooOoo_ ") print("o8888888o") print("88.88") print (" (| - _- |) ") print(" O\\ = /O ") print (" ____/`---'\\____ ") print (" . ' \\| |// `. ") print (" / \\||| : |||// \\ ") print (" / _||||| - :- |||||- \\ ") print (" | | \\\\\\ - /// | | ") print (" | \\_| ''\\---/'' | | ") print (" \\ .-\\__ `-` ___/-. / ") print (" ___`. .' /--.--\\ `. . __ ") print (" ."" '< `.___\\_<|>_/___.' >'"". ") print (" | | : `- \\`.;`\\ _ /`;.`/ - ` : | | ") print (" \\ `-. \\_ __\\ /__ _/ .-` / / ") print (" ======`-.____`-.___\\_____/___.-`____.-'====== ") print (" `=---=' ") print(" ") print(" ................................................") print ("Buddha town building BUG easy") print ("The Buddha said: ") print ("The office in the office building, the programmer in the office; ") print ("The programmer writes the program and trades the program for wine money. ") print ("Only sit on the Internet when sober, and sleep off the Internet when drunk; ") print ("Drunk sober day after day, online and offline year after year.") print ("I hope I die in the computer room, I don't want to bow to the boss; ") print ("Mercedes-Benz BMW you are interested, bus self-programmer. ") print ("People laugh at me for being crazy, I laugh at myself for being too cheap; ") print ("I can't see the pretty girls all over the street, which one belongs to the programmer?") |
Phenomenon after running:
If a program needs to output "Buddha Town Tower" in different places, how should the program be designed?
1 | if condition 1: Output 'Buddha Town Tower' ...(omitted)... if condition 2: Output 'Buddha Town Tower' ...(omitted)... |
If you need to output multiple times, does that mean you have to write this code multiple times?
in conclusion:
If you need a certain piece of code many times when developing a program, but in order to improve the efficiency of writing and the reuse of code, the code block with independent functions is organized into a small module, which is a function.
2, function definition and call
2.1. Definition
The format for defining a function is as follows:
1 | def functionname(): code |
Example:
1 | # Define a function that can complete the function of printing information def printInfo(): print ('------------------------------------------------') print ('Life is too short, I use Python') print ('------------------------------------------------') |
2.2, call
After the function is defined, it is equivalent to having a code with some functions. To make the code execute, it needs to be called.
Calling a function is very simple, you can complete the call through function_name()
.
Example
1 | # After the function is defined, the function will not be executed automatically, you need to call it before you can printInfo() |
Note: The Python call function should be placed after the definition function, and some programming languages can be placed in the front.
2.3. Documentation
1 | def test(a,b): "Used to complete the sum of 2 numbers" print("%d"%(a+b)) |
If you execute
1 | help(test) |
You can see the relevant description of the test
function:
1 | Help on function test in module __main__: test(a, b) Used to complete the sum of 2 numbers (END) |
2.4, function parameters
Assumption: Now we need to define a function that can complete the addition of 2 numbers and print the result. How to design it? Is the code below ok? Are there any flaws?
1 | def add2num(): a = 11 b = 22 c = a+b print(c) |
In order to make a function more general, that is, let it calculate the sum of which two numbers, let it calculate the sum of which two numbers, and let the function receive data when defining the function, which solves this problem, this is parameters to the function**.
2.4.1. Definition
Example:
1 | def add2num(a, b): c = a+b print(c) |
2.4.2, call
Take the call to the add2num(a, b) function above as an example:
1 | def add2num(a, b): c = a+b print(c) add2num(11, 22) #When calling a function with parameters, you need to pass data in parentheses |
Call a run procedure with a parameterized function:
2.4.3, parameter order
1 | >>> def test(a,b): ... print(a,b) ... >>> test(1,2) 1 2 >>> test(b=1,a=2) twenty one >>> >>> test(b=1,2) File "<stdin>", line 1 SyntaxError: positional argument follows keyword argument >>> >>> |
2.4.4. Summary
- Parameters in parentheses during definition, used to receive parameters, are called "formal parameters".
- The parameters in parentheses when calling, which are used to pass to the function, are called "actual parameters".
2.5, function return value
The so-called "return value" is the result given to the caller after the function in the program completes one thing.
2.6, functions with return values
To return the result to the caller in a function, use return
in the function.
The following example:
1 | def add2num(a, b): c = a+b return c |
or
1 | def add2num(a, b): return a+b |
You can also use tuples to return multiple values:
1 | >>> def divide(a, b): ... shang = a//b ... yushu = a%b ... return shang, yushu ... >>> sh, yu = divide(5, 2) >>> lb = divide(5, 2) >>> sh 2 >>> yu 1 >>> lb (2,1) |
2.7, save the return value of the function
At the beginning of this section, in the example of "buying cigarettes", when your son gave you a cigarette, you must have taken it from your son, right? The same is true for programs. If a function returns a piece of data, then If you want to use this data, you need to save it.
An example of the return value of the save function is as follows:
1 | #define function def add2num(a, b): return a+b #Call the function and save the return value of the function by the way result = add2num(100,98) #Because result has saved the return value of add2num, it can be used next print(result) |
3, the types of four functions
Functions can be combined with each other according to whether they have parameters and whether they have return values. There are 4 types:
- no arguments, no return value
- no parameters, return value
- has parameters, no return value
- There are parameters and return values
3.1, no parameters, no return value
This type of function cannot receive parameters and has no return value. In general, use this type of function to print the similar function of the prompt light.
1 | def printMenu(): print('----------------------------') print('xx shabu-shabu ordering system') print('') print(' 1. Lamb Shabu Shabu') print(' 2. Beef Shabu Shabu') print(' 3. Pork Shabu Shabu') print('----------------------------') |
result:
3.2, no parameters, return value
Such functions cannot receive parameters, but can return some data. In general, such functions are used to collect data.
1 | # get temperature def getTemperature(): #Here are some processes for getting the temperature #For simplicity, first simulate returning a data return 24 temperature = getTemperature() print('The current temperature is: %d'%temperature) |
3.3, with parameters, no return value
This type of function can receive parameters, but cannot return data. In general, when setting data for some variables without the result, use this type of function.
3.4, with parameters and return values
Such functions can not only receive parameters, but also return some data. In general, applications such as data processing and needing results use such functions.
1 | # Calculate the cumulative sum of 1~num def calculateNum(num): result = 0 i = 1 while i<=num: result = result + i i+=1 return result result = calculateNum(100) print('The cumulative sum of 1~100 is: %d'%result) |
3.5, small summary
- Functions can be combined with each other according to whether they have parameters and whether they have return values
- When defining a function, it is designed according to the actual functional requirements, so the types of functions written by different developers are different
4, nested calls of functions
4.1. Concept
1 | def testB(): print('---- testB start----') print('This Here is the code executed by the testB function... (omitted)...') print('---- testB end----') def testA(): print('---- testA start----') testB() print('---- testA end----') testA() |
result:
1 | ---- testA start---- ----testB start---- Here is the code executed by the testB function...(omitted)... ----testB end---- ---- testA end---- |
4.2, small summary
- A function calls another function, this is the so-called function nested call.
- If another function B is called in function A, then all tasks in function B are executed before returning to the position where function A was executed last time.
5. Variables
5.1, local variables
As shown below:
- Local variables, which are variables defined inside a function
- Different functions can define local variables with the same name, but each use will not affect
- The role of local variables, in order to temporarily save data, you need to define variables in the function for storage, this is its role
Example:
1 | def test1(): print(a) def test2(): print(a) # Call functions test1() test2() |
5.2, global variables
If a variable can be used in both a function and other functions, such a variable is a global variable
Example:
1 | # define global variables a = 100 def test1(): print(a) def test2(): print(a) # Call functions test1() test2() |
operation result:
1 | 100 100 |
5.4, variable name
See the following code:
Since global variables can be used in all functions, can they be modified?
Example:
5.5, global variables of variable types
1 | >>> a = 1 >>> def f(): ... a += 1 ... print(a) ... >>> f() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in f UnboundLocalError: local variable 'a' referenced before assignment >>> >>> >>> li = [1,] >>> def f2(): ... li.append(1) ... print(li) ... >>> f2() [1, 1] >>> li [1, 1] |
5.6. Summary
- Variables defined outside a function are called
global variables
- Global variables can be accessed in all functions
- If you modify a global variable in a function, you need to use
global
to declare it, otherwise an error occurs - If the name of the global variable and the name of the local variable are the same, then the local variable is called.
- The essence of not modifying global variables when declaring global variables without using
global
in a function is that you cannot modify the pointing of global variables, that is, you cannot point global variables to new data. - For global variables of immutable type, the data pointed to cannot be modified, so global variables cannot be modified without using
global
. - For global variables of mutable type, since the data pointed to can be modified, global variables can also be modified without using
global
.
6, the parameters of the function
6.1, default parameters
When calling the function, the value of the default parameter is considered to be the default value if it is not passed in. The following example will print the default age if age is not passed:
1 | def printinfo( name, age = 35 ): # print any passed string print("Name: ", name) print("Age ", age) # call the printinfo function printinfo(name="9527" ) printinfo( age=9,name="9527" ) |
The output of the above example is:
1 | Name: 9527 Age 35 Name: 9527 Age 9 |
Note: Parameters with default values must be at the end of the parameter list (multiple parameters with default values can be set).
1 | >>> def printinfo(name, age=35, sex): ... print name ... File "<stdin>", line 1 SyntaxError: non-default argument follows default argument |
6.2, variable length parameters
Sometimes it may be desirable for a function to handle more arguments than it was originally declared. These parameters are called variable-length parameters and are not named when they are declared.
The basic syntax is as follows:
1 | def functionname([formal_args,] *args, **kwargs): "function_docstring" function_suite return [expression] |
The variable args with an asterisk (*) will store all unnamed variable parameters, and args is a tuple; while the variable kwargs with ** will store named parameters, that is, parameters in the form of key=value, kwargs is dictionary.
1 | >>> def fun(a, b, *args, **kwargs): ... """Variable parameter demonstration example""" ... print("a = ", a) ... print("b = ", b) ... print("args=", args) ... print("kwargs: ") ... for key, value in kwargs.items(): ... print(key, "=", value) ... >>> fun(1, 2, 3, 4, 5, m=6, n=7, p=8) # Note that the passed parameters correspond to a = 1 b = 2 args = (3, 4, 5) kwargs: p = 8 m = 6 n = 7 >>> >>> >>> >>> c = (3, 4, 5) >>> d = {"m":6, "n":7, "p":8} >>> fun(1, 2, *c, **d) # Note how tuples and dictionaries are passed a = 1 b = 2 args = (3, 4, 5) kwargs: p = 8 m = 6 n = 7 >>> >>> >>> >>> fun(1, 2, c, d) # Note the difference between not adding the asterisk and the above a = 1 b = 2 args = ((3, 4, 5), {'p': 8, 'm': 6, 'n': 7}) kwargs: >>> >>> |
6.3, pass by reference
- Is there any difference when variables of mutable and immutable types are used as function parameters respectively?
- Does Python have pointer parameter transfer similar to C language?
1 | >>> def selfAdd(a): ... """Auto increment""" ... a += a ... >>> a_int = 1 >>> a_int 1 >>> selfAdd(a_int) >>> a_int 1 >>> a_list = [1, 2] >>> a_list [1, 2] >>> selfAdd(a_list) >>> a_list [1, 2, 1, 2] |
Python function parameters are passed by reference (note that it is not passed by value). For immutable types, the dependent variable cannot be modified, so the operation does not affect the variable itself; for variable types, the operation in the function body may change the incoming parameter variable.
1 | >>> def selfAdd(a): ... """Auto increment""" ... a = a + a # We changed this sentence of the function body ... >>> a_int = 1 >>> a_int 1 >>> selfAdd(a_int) >>> a_int 1 >>> a_list = [1, 2] >>> a_list [1, 2] >>> selfAdd(a_list) >>> a_list [1, 2] # Think about why it hasn't changed? |
7. Thanks
Reprinted from:
Zeruns's Blog
Python theoretical knowledge (4) functions and variables
Comments