Detailed explanation of basic knowledge of functions

1. What is a function

A function is an organized, reusable piece of code that implements a single or related function. Functions can improve the modularity of the application and the reuse rate of the code. In the previous article, we have used the built-in functions provided by python, such as print(). But you can also create your own functions, which are called user-defined functions.

2. Custom functions

(1) A function code block begins with the def keyword, followed by the function identifier name and parentheses ().
(2) Any incoming parameters and independent variables must be placed between parentheses, which can be used to define parameters.
(3) The first statement of the function can optionally use the documentation string—used to store the function description.
(4) The function content starts with a colon : and is indented.
(5) return [expression] end the function, optionally return a value to the caller, return without expression is equivalent to returning None.
(6) Syntax format:

def Function name(parameter list):
    function body
# demo
def Max(num1, num2):
    if num1 > num2:
        return num1
        return num2

print('the max value is:> ', Max(1, 4))

3. Parameter passing

Note, if the reader has been exposed to c/c++, then this part is unnecessary, it is equivalent to the value transfer and reference transfer in the c/c++ function.
(1) Mutable and immutable objects
In python, str, tuple, and number are immutable objects, while list, dict, and set are modifiable objects.
[a]. Immutable type
The variable is assigned a=5 and then assigned a=10. Here, an int value object 10 is actually newly generated, and then a points to it, while 5 is discarded. Instead of changing the value of a, it is equivalent to newly generating a. To put it bluntly, the memory space occupied by a twice is different.

# Get the memory space occupied by the variable a through id(), and find that the memory space occupied by the variable a is not the same twice, 
# It shows that the second assignment is not simply to modify the value of a in the first time, 
# Instead, the memory space is re-opened for storage.
a = 5
a = 10

[b]. Mutable type
Variable assignment la=[1,2,3,4] and then assignment la[2]=222 is to change the value of the third element of la, la itself does not move, but part of its internal value is modified.
To put it bluntly, it is to operate on the same la.

# The operation of la[2] here is actually the operation of la at the beginning,
# The operation is the same memory space.
la = [1,2,3,4]
la[2] = 222

[c]. Parameter passing summary
a) Immutable types
Similar to value passing in c/c++, such as integers, strings, tuples. For example, fun(a), only the value of a is passed, and the a object itself is not affected. If the value of a is modified inside fun(a), an object of a is newly generated.
Actual parameters: When a function is called, the parameters in parentheses after the function name are called "actual parameters", or "actual parameters" for short.
Formal parameters: When defining a function, the variables in parentheses after the function name are called "formal parameters", or "formal parameters" for short.

# In the following functions, num is called a formal parameter, and number is called an actual parameter.
def test(num):
# It can be seen that before and after calling the function, the formal parameter and the actual parameter point to the same object (id() is the same),
# After the parameter is modified inside the function, the parameter points to a different id.
def change(number):
    print(id(number))  # point to the same object
    number = 10
    print(id(number))  # A new object, new memory space

number = 1

b) mutable type
Similar to reference passing in c++, such as lists, dictionaries, and collections. For example, fun(la) is to actually pass la to the past, and the modified la outside fun will also be affected.

# We change the incoming dict inside the function, and find that the external dict is also changed synchronously. 
# It shows that both the actual parameter and the formal parameter are the same object, and both point to the same memory space.
def changeDict(d):
    d['num'] = 102

dict = {"num": 101, "name": "Zhang"}

4. Function parameters

(1) Mandatory parameters
Required arguments must be passed to the function in the correct order. The number at call must be the same as at declaration.

# When calling the test() function, a parameter must be passed in, otherwise an error will be reported
def test(str):

test()	# If no parameters are passed in when calling the function, an error will be reported

(2) Keyword arguments
Keyword parameters are closely related to function calls, and function calls use keyword parameters to determine the incoming parameter values. Using keyword arguments allows the function to be called in a different order than it was declared, because the python interpreter is able to match the parameter name with the parameter value.

# If we stipulate that the first parameter of the function is a string type, and the second parameter is an integer type, 
# The third parameter is a list type, so in general, we should follow the prior
# Objects are passed in in the specified order, but since we specified keyword arguments when calling the function, 
# So the order can be written freely, because the python interpreter can match the parameter value with the parameter name.
def test(str, num, ls):
    print(str, num, id)

test(num=191, ls=[1,2], str="HelloWorld")

(3) Default parameters
When calling a function, if no parameters are passed, default parameters will be used.

# A default value is specified for the parameter age. When calling the function, if the third parameter is not passed in,
# The default will be used. 
def printStudent(num, name, age=18):
    print('student info is:>', num, name, age)

printStudent(101, 'Zhang')	# If the third parameter is not specified, the default value will be used
printStudent(102, 'Wang', 19)	# The third parameter is specified

(4) Indefinite length parameter
When defining a function, the number of parameters passed into the function may not be determined in advance, at this time, parameters of variable length can be used to receive them.
(a) Format 1
Parameters with an asterisk * will be imported in the form of tuples, storing all unnamed variable parameters.

# Format
def fun([formal_args,] *var_args_tuple ):
# demo
def params(arg1, *vartuple):
    print(arg1, end=", ")
    print(vartuple)		# tuple
    for item in vartuple:
    	print(item, end=",")
params(10, 20, 30, 40)

(b) Format 2
Parameters with two asterisks ** will be imported as a dictionary.

# Format
def fun([formal_args,] **var_args_dict ):
# demo
# Because the remaining parameters are imported in the form of a dictionary, the remaining parameters must be passed when calling the function
# Call in the form of key=value, otherwise an error will be reported
def Params(arg1, **var_args_dict):

Params(1, num=101, name='Zhang', age=18)

(c) other
When declaring a function, the asterisk * can appear alone in the parameter.
If the asterisk * appears alone, the parameters after the asterisk * must be passed in with keywords.

def sum(a, b, *, c):
	return a + b + c

# sum(1,2,3)	# error
sum(1,2,c=3)	# correct

5. return statement

The return [expression] statement is used to exit a function, optionally returning an expression to the caller.
If the function does not return any value, it is equivalent to returning None.

6. Nesting of functions

Unlike c/c++, functions in python can be nested.

# Come see a demo
def foo(factor):
    def bar(number):
        return number * factor
    return bar  # returns a function
x = foo(2)
print("the result is:> ", x(5))
print("the result is:> ", (foo(2))(5))

Here, one function (bar()) is inside another function (foo()), and the outer function returns the inner function. That is, return a function instead of calling it.
It is important that the returned function has access to the scope in which it was defined.
In fact, we call a function like bar() that stores the scope it is in a closure.

Tags: Python

Posted by zenabi on Tue, 24 Jan 2023 00:31:42 +0300