Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
First, variable reference
- Variables and data are stored in memory
- in
Python
中 Function parameter passingAs well asThe return valueAll is to rely onreferenceThe passed
1.1 Concept of reference
In Python
- Variables and data are stored separately
- Data is stored in a location in memory
- Variables hold the memory address of the data
- The address of the recorded data in a variable is called a reference
- use
id()
The function can view where data is stored in a variableMemory address
Note: If the variable is already defined, assigning a value to a variable essentially changes the reference to the data
- The variable no longer refers to the previous data
- The variable is changed to a reference to the newly assigned data
1.2 Examples of variable references
In Python, variable names are similar to post-it notes attached to data
- Define an integer variable
a
And assign the value to1
code | graphic |
---|---|
a = 1 |
- The variable
a
The assignment for2
code | graphic |
---|---|
a = 2 |
- Define an integer variable
b
, and the variablea
Assigns the value tob
code | graphic |
---|---|
b = a |
The variable B is the second label attached to the number 2
1.3 Passing of parameters and return values of functions
In Python, function arguments/return values are passed by reference
In [1] :def demo(num) :. :... :print('num=', num, 'address:.id(num)) ... :... : result =100. :... :print('result=', result, 'address:.id(result)) ... :... :returnresult ... : In [2]: a = 10
In [3] :print('a=', a, 'address:.id(a))
a= 10Address:140704168770912
In [4]: r = demo(a)
num= 10Address:140704168770912
result= 100Address:140704168773792
In [5] :id(r)
Out[5] :140704168773792
Copy the code
The address of a is the same as that of num, and the address of r is the same as that of result
Mutable and immutable types
- Immutable typeData in memory cannot be modified:
- Numeric types
int
.bool
.float
.complex
.long(2.x)
- string
str
- tuples
tuple
- Numeric types
- The variable type, the data in memory can be modified:
- The list of
list
- The dictionary
dict
- The list of
Immutable data type test
In [13]: x = 1
In [14] :id(x)
Out[14] :140704168770624
In [15]: x = 'hello'
In [16] :id(x)
Out[16] :2377344402928
In [17]: x = [1.2.3]
In [18] :id(x)
Out[18] :2377344895240
In [19]: x = [3.2.1]
In [20] :id(x)
Out[20] :2377342416648
Copy the code
Immutable type. Data in memory cannot be modified. When a variable is reassigned, it does not modify the data currently referenced
- The variable no longer refers to the previous data
- The variable is changed to a reference to the newly assigned data
Variable data type tests
In [20]: li = [1.2.3]
In [21] :Memory address after list definition
In [22] :id(li)
Out[22] :2377344541640
In [23]: li.append(Awesome!)
In [24]: li.pop(0)
Out[24] :1
In [25]: li.remove(2)
In [26]: li[0] = 10
In [27] :# list the memory address after modification
In [28]: li
Out[28] : [10.Awesome!]
In [29] :id(li)
Out[29] :2377344541640 The internal elements have changed, but the memory address remains the same
Copy the code
info_dict = {'name': 'ithui'}
print('Address after dictionary definition'.id(info_dict))
info_dict['age'] = 22
info_dict.pop('name')
info_dict['name'] = 'hui'
print('Address after modifying dictionary data'.id(an info_dict)) = = = = = = = = = = = = = the result as follows = = = = = = = = = = = = = definitions dictionary after the address1907533547384Modify the address of the dictionary data1907533547384
Copy the code
Note:
- Mutable type data changes are implemented through methods
- If I assign a new value to a variable of variable type,References will change
- The variable no longer refers to the previous data
- The variable is changed to a reference to the newly assigned data
- A dictionary of
key
Only immutable types of data can be used
The hash(hash)
Python
There’s a name built into it calledhash(o)
The function of- Accepts data of an immutable type as a parameter
- The return result is an integer
The hash
It is a kind ofalgorithm, its function is to extract dataCharacteristic code (fingerprint)- The same content gets the same result
- Different content gets different results
- in
Python
To set the dictionaryKey/value pairWill be the first tokey
forhash
Have you decided how to store the dictionary data in memory for conveniencesubsequentOperations on dictionaries:Add, delete, change, search- The key/value pair
key
Must be immutable type data - The key/value pair
value
It can be any type of data
- The key/value pair
Local variables and global variables
- Local variables are variables defined inside a function and can only be used inside a function
- A global variable is a variable defined outside a function (not inside a function) that can be used inside all functions
Tip: in most other development languages, global variables are not recommended — the range of variables is too large to maintain!
3.1 Local variables
- Local variables are variables defined inside a function and can only be used inside a function
- After a function is executed, local variables inside the function are reclaimed by the system
- Different functions can define local variables with the same name, but have no effect on each other
1) The role of local variables
- Used within a function to temporarily save data that needs to be used within the function
2) The life cycle of local variables
- The so-called life cycle is the process from the creation of a variable to its recycling by the system
- Local variables are created at function execution time
- Local variables are reclaimed by the system after the function is executed
- Local variables can be used to store temporarily used data within a function during its lifetime
3.2 Global Variables
- A global variable is a variable defined outside a function that can be used inside all functions
Define a global variable
num = 10
def demo1() :
print(num)
def demo2() :
print(num)
demo1()
demo2()
print("over") ============= The result is as follows =============10
10
over
Copy the code
Note: When a function is executed, it needs to handle variables:
- First check if there is a local variable with the specified name inside the function. If so, use it directly
- If not, check whether a global variable with the specified name exists outside the function. If so, use the global variable directly
- If not, program error!
1) Functions cannot be modified directlyReferences to global variables
-
A global variable is a variable defined outside a function (not inside a function) that can be used inside all functions
-
Inside a function, the corresponding data can be retrieved by reference to a global variable
-
However, it is not allowed to change a reference to a global variable directly — the value of a global variable is changed using an assignment statement
num = 10
def demo1() :
print("demo1".center(30.'='))
# define a local variable, do not change to a global variable, just the same variable name
num = 100
print(num)
def demo2() :
print("demo2".center(30.'='))
print(num)
demo1()
demo2()
print("over")
# The result is as follows
============demo1=============
100
============demo2=============
10
over
Copy the code
Note: only a local variable is defined inside the function with the same name — you cannot change the value of a global variable directly inside the function
2) Modify the value of a global variable inside a function
- If you need to modify a global variable in a function, use this parameter
global
To declare
num = 10
def demo1() :
print("demo1".center(30.'='))
The # global keyword tells the Python interpreter that num is a global variable
global num
# define a local variable, do not change to a global variable, just the same variable name
num = 100
print(num)
def demo2() :
print("demo2".center(30.'='))
print(num)
demo1()
demo2()
print("over")
# The result is as follows
============demo1=============
100
============demo2=============
100
over
Copy the code
3) Location of global variable definition
- because
Python
The interpreter interprets execution from top to bottom, so to ensure that all functions use global variables correctly, it shouldDefine global variables above other functions
4) Suggestions for naming global variables
- Code is written not just for machines to execute, but for programmers themselves. Therefore, to avoid confusion between local and global variables, it is common to increment global variables when defining them
g_
orgl_
“, or all caps.
The tail language
✍ Code writes the world and makes life more interesting. ❤ ️
✍ thousands of rivers and mountains always love, ✍ go again. ❤ ️
✍ code word is not easy, but also hope you heroes support. ❤ ️