Article Directory
foreword
We have learned the basic use of python functions earlier, so today I will continue to take you to understand more operations of python functions.
variable scope
Variables are divided into local variables and global variables, and the scope of the two variables is different.
- Local variables refer to variables defined inside the function body, which only take effect inside the function body.
- A global variable is a variable that can take effect both inside and outside a function.
local variable
def test1():
a = 100 # 这里a属于局部变量
print(a)
After exiting the function body, the local variable a will be destroyed.
def test1():
a = 100
print(a)
print(a)
global variable
a = 100
def test1():
print(f'在函数内部使用全局变量{
a}')
test1()
print(f'在函数外部使用全局变量{
a}')
If all variables are modified outside the function body, the global variables will be modified, so what happens if we modify the global variables inside the function body?
a = 100
def test1():
a = 200
print(a)
test1()
print(a)
It can be found that modifying the global variable inside the function body only modifies the variable inside the function body. In fact, the global variable has not changed, that is to say, the modification inside the function body is actually a local variable, so how to modify the global variable inside the function body Woolen cloth?
global 变量
Declare this variable as a global variable, and then modify the global variable.
a = 100
def test1():
global a
a = 200
print(a)
test1()
print(a)
function return value
The return value of the function we mentioned earlier is one data, so what should we do if we want to return multiple data?
- Use commas, to separate multiple data, but these multiple data will always be merged into a tuple and returned.
- Return multiple data in the form of list, tuple, dictionary, set.
return with a comma,
def test1():
return 1,2,3
print(test1())
return as a list
def test1():
return [1,2,3]
print(test1())
returned as a tuple
def test1():
return (1,2,3)
print(test1())
return as a set
def test1():
return {
1,1,2,3}
print(test1())
In this regard, we can choose which form to return the data according to our needs
function parameters
There are four ways to pass parameters to a function:
- position parameter
- Keyword parameter passing
- default parameter
- variable length parameter
1. Positional parameters
When calling a function, parameters are passed according to the order and number of parameters defined by the function.
def test1(name,age,gender):
print(f'姓名:{
name} 年龄:{
age} 性别:{
gender}')
test1('zhangsan',18,'man')
When the number of parameters passed in is different from the number of parameters when the function is defined, an error will be reported.
def test1(name,age,gender):
print(f'姓名:{
name} 年龄:{
age} 性别:{
gender}')
test1('zhangsan',18)
When passing parameters, the order is different from the order of parameters at the time of definition, and it can be run through, but the code is meaningless.
def test1(name,age,gender):
print(f'姓名:{
name} 年龄:{
age} 性别:{
gender}')
test1(18,'zhangsan','man')
2. Keyword arguments
Formulated in the form of "key = value", it can make the function clearer and easier to use, and it does not need to follow the order of passing parameters.
def test1(name,age,gender):
print(f'姓名:{
name} 年龄:{
age} 性别:{
gender}')
test1(gender = 'man',name = 'zhangsan',age = 18)
When using keywords to pass parameters, there can be positional parameters, but the positional parameters must be before the keyword parameters. The positional parameters must correspond to the positions of the parameters when the function is defined.
def test1(name,age,gender):
print(f'姓名:{
name} 年龄:{
age} 性别:{
gender}')
test1('zhangsan',gender = 'man',age = 18)
When the positional parameter does not correspond to the parameter when the function is defined, an error will be reported.
def test1(name,age,gender):
print(f'姓名:{
name} 年龄:{
age} 性别:{
gender}')
test1('man',name = 'zhangsan',age = 18)
3. Default parameters
Default parameters are also called default parameters, which are used to define functions and provide default values for parameters. When calling a function, the value of the default parameter may not be passed (note: all positional parameters must appear before the default parameter, including function definition and call).
When the function is defined, we can specify a default value for the parameter, so that when we do not pass in a value for this parameter, this parameter will use the default value, and if we pass in data for this parameter, this parameter will also become The data we pass in.
def test1(name,age,gender = 'man'):
print(f'姓名:{
name} 年龄:{
age} 性别:{
gender}')
test1('zhangsan',18)
def test1(name,age,gender = 'man'):
print(f'姓名:{
name} 年龄:{
age} 性别:{
gender}')
test1('zhangsan',18,'woman')
test1(age = 19,name = 'lisi')
Once you start using default parameters in function definitions, all parameters following the default parameter must be default parameters. In other words, all parameters without default values (positional parameters) must appear before parameters with default values (keyword parameters).
def test1(name,age = 18,gender):
print(f'姓名:{
name} 年龄:{
age} 性别:{
gender}')
test1('zahngsan','man')
4. Variable length parameter
Indefinite length parameters are also called variable parameters. It is used in scenarios where it is uncertain how many parameters will be passed when calling (it is also possible to pass no parameters). At this time, it will be very convenient to use packing positional parameters or packing keyword parameters for parameter passing.
1) Package position transfer
def 函数名(*args):
This * cannot be omitted, it is a sign of package position transfer, and the args behind can be replaced, but it is recommended to use args in real life, because the bottom layer of python also uses args.
Arguments passed using positional wrapping will be combined into a tuple passed to the function.
def test1(*args):
print(args)
test1()
test1(1)
test1(1,2)
2) Passing of wrapped keywords
def 函数名(**args):
When passing parameters, pass them in the form of "key = value". And when parameters are passed in the form of wrapped keywords, these parameters will be merged into a dictionary and passed into the parameters.
def test1(**args):
print(args)
test1(name = 'zhangsan',age = 18,gender = 'man')
The above package position transfer and package key transfer are both a process of packaging, and we can also carry out the process of unpacking.
unpack
1) Tuple unpacking
def test1():
return 100,200
a,b = test1()
print(a)
print(b)
Note here: During the unpacking process, the number of variables received must be the same as the number of elements in the tuple.
2) Dictionary unpacking
Dictionary unpacking, the key of the dictionary is stored in the variable, we can operate the value according to the key obtained by unpacking
dict1 = {
'name':'zhangsan','age':18,'gender':'man'}
a,b,c = dict1
print(a)
print(b)
print(c)
print(dict1[a])
print(dict1[b])
print(dict1[c])
Swap the value of the variable
In python, there are two common ways to exchange the values of two variables.
- Use the median method.
- a,b = b,a
Using the median method
a = 100
b = 200
c = 0
c = a
a = b
b = c
print(a)
print(b)
Use the intermediate value c to store one of the data to prevent it from being replaced during the exchange.
b,a = a,b
a = 100
b = 200
a,b = b,a
print(a)
print(b)
quote
In Python, references play a pivotal role in object handling.
-
Object assignment: In Python, when you create an object and assign it a variable name, the variable name is just a reference to that object, not the object itself. For example, when you create a list a = [1, 2, 3], a is actually a reference to the list [1, 2, 3].
-
Function parameter passing: Python uses pass-by-reference to pass parameters to functions. So, if you change the value of the passed object inside the function, the value of the object outside the function will also change. It should be noted that for immutable types (such as integers, strings, and tuples), due to their immutable characteristics, the operations performed on them inside the function will not affect the actual external objects.
-
Sharing and copying: The assignment of objects in Python is actually creating a new reference instead of creating a brand new object. For example, when you write b = a, you're actually just creating a new reference to b, not a new list. This is the so-called shallow copy (shallow copy). If you want to create a deep copy (deep copy) of an object, that is, a brand new object, you can use the deepcopy function of the copy module. Especially for complex data structures such as lists, dictionaries or custom objects, it is very important to understand the reference model in Python.
Let’s understand the third point here first, and then explain it to you later.
Before understanding references, we need to understand which data types are mutable data types and which types are immutable types in python.
Mutable and immutable data types
mutable type
- the list
- dictionary
- gather
immutable type
- integer
- floating point
- string
- tuple
We use a piece of code to understand what a reference is.
id()
A function can know the address of what the reference refers to.
a = 1
b = a
print(id(a))
print(id(b))
a refers to 1 and b refers to the reference that a refers to.
a = 1
b = a
a = 2
print(a)
print(b)
print(id(a))
print(id(b))
Here, because the int type is an immutable type, when the value of a changes from 1 to 2, another space will be opened to store 2, and then a will be referenced to point to this address.
Doesn't this happen when the type pointed to by the reference is a mutable type?
a = [1,2,3]
b = a
a.append(4)
print(a)
print(b)
print(id(a))
print(id(b))
We see that when the reference is a mutable data type, when the data content is changed, the referenced address will not change.
We can pass parameters by reference as parameters.
def test1(a):
print(id(a))
a = 2
print(id(a))
a = 1
print(id(a))
test1(a)
print(id(a))
print(a)
Here, the reference a inside the function is actually a temporary variable, and the data type of a reference is int type, which is an immutable type. When changing the value of the temporary variable a, an additional int type memory with a value of 2 will be created , and then the temporary variable a points to this memory. When the function exits, the temporary variable a will be destroyed, and the printed value of a is still the previous value.
When the data type of the incoming reference reference is a mutable type
def test1(a):
print(id(a))
a[0] = 4
print(id(a))
a = [1,2,3]
print(id(a))
test1(a)
print(id(a))
print(a)