Introduction to Python variable scope and list

Time:2021-10-20

Variable scope

Variables are limited by scope

Classification: by scope

  • Global: defined outside the function
  • Local: defined inside a function

Scope of variable

  • Global variable: valid in the whole global scope
  • Global variables can be used locally (that is, variables defined outside the function can be accessed inside the function)
  • Local variables can be used in a local scope
  • Local variables cannot be used globally

Legb principle

  • L (local) local scope
  • E (enclosing function local) scope of external nested function
  • G (Global module) function defines the scope of the module
  • B (build in): scope of Python built-in module
?
1
2
3
4
5
6
7
8
9
10
11
12
13
#Think A1 is global
a1 = 100
 
def fun():
 print(a1)
 print("I am in fun")
 #The scope of action of A2 is fun
 a2 = 99
 print(a2)
 
print(a1)
fun()
# print(a2)

100
100
I am in fun
99

Promote local variables to global variables

Using global

The case is as follows

?
1
2
3
4
5
6
7
8
9
10
def fun():
 global b1
 b1 = 100
 print(b1)
 print("I am in fun")
 b2 = 99
 print(b2)
 
fun()
print(b1)

100
I am in fun
99
100

Global, local function

Local and global variables can be displayed through globals and locals

Refer to the case

?
1
2
3
4
5
6
7
8
9
10
11
#Globals and locals
#Globals and locals are called built-in functions
a = 1
b = 2
 
def fun(c,d):
 e = 111
 print("Locals={0}".format(locals()))
 print("Globals={0}".format(globals()))
  
fun(100, 200)

Locals={‘c’: 100, ‘d’: 200, ‘e’: 111}
Where the globe is at the end of the where it ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ” ”’the end of the gluglugluglugluglugluuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuph[”, ‘# think A1 is global \ Na1 = 100 \ n \ nDef fun(): \ n     print(a1)\n     print(“I am in fun”)\n     a2 = 99\n     print(a2)\n     \ Nprint (A2), ‘# considers A1 to be global \ Na1 = 100 \ n \ nDef fun(): \ n     print(a1)\n     print(“I am in fun”)\n     a2 = 99\n     print(a2)\n     \ Nprint (A1), ‘# considers A1 to be global \ Na1 = 100 \ n \ nDef fun(): \ n     print(a1)\n     print(“I am in fun”)\n     a2 = 99\n     print(a2)\n     \ Nprint (A1) \ nfun() \ n# print (A2), ‘# considers A1 global \ Na1 = 100 \ n \ nDef fun(): \ n     print(a1)\n     print(“I am in fun”)\n     a2 = 99\n     print(a2)\n     \ Nprint (A1) \ nfun() \ nprint (A2), ‘# consider A1 global \ Na1 = 100 \ n \ nDef fun(): \ n     print(a1)\n     print(“I am in fun”)\n     a2 = 99\n     print(a2)\n     \ nprint(a1)\nfun()\n# print(a2)’, ‘def fun():\n     b1 = 100\n     print(b1)\n     print(“I am in fun”)\n     b2 = 99\n     print(b2)\n     \ nfun()’, ‘def fun():\n     global b1 = 100\n     print(b1)\n     print(“I am in fun”)\n     b2 = 99\n     print(b2)\n\nprint(b1)’, ‘def fun():\n     global b1 \n     b1 = 100\n     print(b1)\n     print(“I am in fun”)\n     b2 = 99\n     print(b2)\n\nprint(b1)’, ‘def fun():\n     global b1 \n     b1 = 100\n     print(b1)\n     print(“I am in fun”)\n     b2 = 99\n     print(b2)\n\nprint(b1)’, ‘def fun():\n     global b1 \n     b1 = 100\n     print(b1)\n     print(“I am in fun”)\n     b2 = 99\n     Print (B2) \ n \ nprint (B1), ‘# globals and locales \ Na = 1 \ NB = 2 \ n \ nDef fun (C, d): \ n     e = 111\n     print(“Locals={0}”.format(locals()))\n     print(“Globals={0}”.format(globals())\n           \ Nfun (100, 200), ‘# global and locales \ Na = 1 \ NB = 2 \ n \ nDef fun (C, d): \ n     e = 111\n     print(“Locals={0}”.format(locals()))\n     print(“Globals={0}”.format(globals()))\n           \ Nfun (100, 200), ‘# global and locales \ n# global and locales are called built-in functions \ Na = 1 \ NB = 2 \ n \ nDef fun (C, d): \ n     e = 111\n     print(“Locals={0}”.format(locals()))\n     print(“Globals={0}”.format(globals()))\n           \ Nfun (100, 200) ‘],’ _oh ‘: {},’ _dh ‘: [‘d: \ \ Jupiter \ \ nootbook \ \ notes’],’ in ‘: [‘ ‘,’ # considers A1 global \ Na1 = 100 \ n \ nDef fun(): \ n     print(a1)\n     print(“I am in fun”)\n     a2 = 99\n     print(a2)\n     \ Nprint (A2), ‘# considers A1 to be global \ Na1 = 100 \ n \ nDef fun(): \ n     print(a1)\n     print(“I am in fun”)\n     a2 = 99\n     print(a2)\n     \ Nprint (A1), ‘# considers A1 to be global \ Na1 = 100 \ n \ nDef fun(): \ n     print(a1)\n     print(“I am in fun”)\n     a2 = 99\n     print(a2)\n     \ Nprint (A1) \ nfun() \ n# print (A2), ‘# considers A1 global \ Na1 = 100 \ n \ nDef fun(): \ n     print(a1)\n     print(“I am in fun”)\n     a2 = 99\n     print(a2)\n     \ Nprint (A1) \ nfun() \ nprint (A2), ‘# consider A1 global \ Na1 = 100 \ n \ nDef fun(): \ n     print(a1)\n     print(“I am in fun”)\n     a2 = 99\n     print(a2)\n     \ nprint(a1)\nfun()\n# print(a2)’, ‘def fun():\n     b1 = 100\n     print(b1)\n     print(“I am in fun”)\n     b2 = 99\n     print(b2)\n     \ nfun()’, ‘def fun():\n     global b1 = 100\n     print(b1)\n     print(“I am in fun”)\n     b2 = 99\n     print(b2)\n\nprint(b1)’, ‘def fun():\n     global b1 \n     b1 = 100\n     print(b1)\n     print(“I am in fun”)\n     b2 = 99\n     print(b2)\n\nprint(b1)’, ‘def fun():\n     global b1 \n     b1 = 100\n     print(b1)\n     print(“I am in fun”)\n     b2 = 99\n     print(b2)\n\nprint(b1)’, ‘def fun():\n     global b1 \n     b1 = 100\n     print(b1)\n     print(“I am in fun”)\n     b2 = 99\n     Print (B2) \ n \ nprint (B1), ‘# globals and locales \ Na = 1 \ NB = 2 \ n \ nDef fun (C, d): \ n     e = 111\n     print(“Locals={0}”.format(locals()))\n     print(“Globals={0}”.format(globals())\n           \ Nfun (100, 200), ‘# global and locales \ Na = 1 \ NB = 2 \ n \ nDef fun (C, d): \ n     e = 111\n     print(“Locals={0}”.format(locals()))\n     print(“Globals={0}”.format(globals()))\n           \ Nfun (100, 200), ‘# global and locales \ n# global and locales are called built-in functions \ Na = 1 \ NB = 2 \ n \ nDef fun (C, d): \ n     e = 111\n     print(“Locals={0}”.format(locals()))\n     print(“Globals={0}”.format(globals()))\n           \ nfun(100, 200)’], ‘Out’: {} ,’get_ipython ‘: < bound method interactive shell. Get_ipython of < ipykerner. Zmqshell. Zmqinteractive shell object at 0x000001b07af18ba8 > >,’exit’: < IPython. Core. Autocall. Zmqexitautocall object at 0x000001b07d7398d0 >,’Quit ‘: < IPython. Core. Autocall. Zmqexitautocall object at 0x000001b07d7398d0 >,’u’: ”,’u ‘:’ ‘,’u’: ”,’u I ‘:’ # global and local\ na = 1\nb = 2\n\ndef fun(c,d):\n     e = 111\n     print(“Locals={0}”.format(locals()))\n     print(“Globals={0}”.format(globals()))\n           \ Nfun (100, 200), ‘_ii’: ‘# global and locales \ Na = 1 \ NB = 2 \ n \ nDef fun (C, d): \ n     e = 111\n     print(“Locals={0}”.format(locals()))\n     print(“Globals={0}”.format(globals())\n           \ nfun(100, 200)’, ‘_iii’: ‘def fun():\n     global b1 \n     b1 = 100\n     print(b1)\n     print(“I am in fun”)\n     b2 = 99\n     Print (B2) \ n \ nprint (B1), ‘_i1’: ‘# think A1 is global \ Na1 = 100 \ n \ nDef fun(): \ n     print(a1)\n     print(“I am in fun”)\n     a2 = 99\n     print(a2)\n     \ Nprint (A2), ‘A1’: 100, ‘fun’: < function fun at 0x000001b07d8c41e0 >, ‘_i2’: ‘# considers A1 global \ Na1 = 100 \ n \ nDef fun(): \ n     print(a1)\n     print(“I am in fun”)\n     a2 = 99\n     print(a2)\n     \ Nprint (A1), ‘_i3’: ‘# considers A1 global \ Na1 = 100 \ n \ nDef fun(): \ n     print(a1)\n     print(“I am in fun”)\n     a2 = 99\n     print(a2)\n     \ Nprint (A1) \ nfun() \ n# print (A2), ‘_i4’: ‘# considers A1 global \ Na1 = 100 \ n \ nDef fun(): \ n     print(a1)\n     print(“I am in fun”)\n     a2 = 99\n     print(a2)\n     \ Nprint (A1) \ nfun() \ nprint (A2), ‘_i5’: ‘# considers A1 global \ Na1 = 100 \ n \ nDef fun(): \ n     print(a1)\n     print(“I am in fun”)\n     a2 = 99\n     print(a2)\n     \ nprint(a1)\nfun()\n# print(a2)’, ‘_i6’: ‘def fun():\n     b1 = 100\n     print(b1)\n     print(“I am in fun”)\n     b2 = 99\n     print(b2)\n     \ nfun()’, ‘_i7’: ‘def fun():\n     global b1 = 100\n     print(b1)\n     print(“I am in fun”)\n     b2 = 99\n     print(b2)\n\nprint(b1)’, ‘_i8’: ‘def fun():\n     global b1 \n     b1 = 100\n     print(b1)\n     print(“I am in fun”)\n     b2 = 99\n     print(b2)\n\nprint(b1)’, ‘_i9’: ‘def fun():\n     global b1 \n     b1 = 100\n     print(b1)\n     print(“I am in fun”)\n     b2 = 99\n     print(b2)\n\nprint(b1)’, ‘_i10’: ‘def fun():\n     global b1 \n     b1 = 100\n     print(b1)\n     print(“I am in fun”)\n     b2 = 99\n     Print (B2) \ n \ nprint (B1), ‘_i11’: ‘# global and locales \ Na = 1 \ NB = 2 \ n \ nDef fun (C, d): \ n     e = 111\n     print(“Locals={0}”.format(locals()))\n     print(“Globals={0}”.format(globals())\n           \ Nfun (100, 200), ‘_i12’: ‘# global and locales \ Na = 1 \ NB = 2 \ n \ nDef fun (C, d): \ n     e = 111\n     print(“Locals={0}”.format(locals()))\n     print(“Globals={0}”.format(globals()))\n           \ Nfun (100, 200), ‘a’: 1, ‘B’: 2, ‘_i13’: ‘# globals and locales \ n# globals and locales are called built-in functions \ Na = 1 \ NB = 2 \ n \ nDef fun (C, d): \ n     e = 111\n     print(“Locals={0}”.format(locals()))\n     print(“Globals={0}”.format(globals()))\n           \ nfun(100, 200)’}

Eval() function

Execute a string as an expression and return the result after the expression is executed

Syntax:

          eval(string_code, globals=None, locals=None)

Exec() function

Similar to the eval function, but does not return results

Syntax:

          exec(string_code, globals=None, locals=None)

?
1
2
3
4
5
6
7
8
9
x = 100
y = 200
#Execute x + y
# z = x + y
z1 = x + y
z2 = eval("x+y")
 
print(z1)
print(z2)

300
300

?
1
2
3
4
5
6
7
8
9
10
11
12
#Exec case
x = 100
y = 200
#Execute x + y
# z = x + y
z1 = x + y
#1. Pay attention to the writing of quotation marks in the string
#2. Compare the exec execution result with the code execution result
z2 = exec("print('x+y:',x+y)")
 
print(z1)
print(z2)

x+y: 300
300
None

Recursive function

  • Function calls itself directly or indirectly
  • Advantages: concise and easy to understand
  • Disadvantages: limited recursion depth and large resource consumption
  • Python has a limit on the recursion depth. If the limit is exceeded, an error will be reported
  • When writing recursive programs, be sure to pay attention to the end conditions
?
1
2
3
4
5
6
7
8
9
10
11
12
#Recursive call depth limit code
 
x = 0
def fun():
 global x
 x += 1
 print(x)
 #The function calls itself
 fun()
 
#Call function
# fun()

—————————————————————————

RecursionError                            Traceback (most recent call last)

<ipython-input-23-bfedb7e396bc> in <module>
     10
     11 # call function
—> 12 fun()


<ipython-input-23-bfedb7e396bc> in fun()
      7     print(x)
      eight      # The function calls itself
—-> 9     fun()
     10
     11 # call function


… last 1 frames repeated, from the frame below …


<ipython-input-23-bfedb7e396bc> in fun()
      7     print(x)
      eight      # The function calls itself
—-> 9     fun()
     10
     11 # call function


RecursionError: maximum recursion depth exceeded while calling a Python object

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#Fibonacci sequence
#A list of numbers. The first value is 1, and the second is also 1. Starting from the third, the value of each number is equal to the sum of the values of the first two numbers
#The mathematical formula is: F (1) = 1, f (2) = 1, f (n) = f (n - 1) + F (n - 2)
#For example: 1, 1, 2, 3, 5, 8, 13
 
#N means finding the value of the Fibonacci sequence of the nth number
def fib(n):
 if n == 1 or n == 2:
  return 1
 elif n > 0:
  return fib(n-1) + fib(n-2)
 else:
  return None
 
print(fib(3))
print(fib(5))
print(fib(10))
print(fib(-1))
print(fib(1))

2
5
55
None
1

Built in data structure (variable type)

  • list
  • set
  • dict
  • tuple

List

A combination of sequential data

Create list

  • Empty list
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#1. Create an empty list
l1 = []
#Type is a built-in function that prints out the type of the variable
print(type(l1))
print(l1)
 
#2. Create a list with values
l2 = [100]
print(type(l2))
print(l2)
 
#3. Create a list with multiple values
l3 = [2,3,5,5,9,7,8,]
print(type(l3))
print(l3)
 
#4. Use list ()
l4 = list()
print(type(l4))
print(l4)

<class ‘list’>
[]
<class ‘list’>
[100]
<class ‘list’>
[2, 3, 5, 5, 9, 7, 8]
<class ‘list’>
[]

List common operations

visit

  • Use subscript operation (index)
  • The list starts at 0

Slice operation

  • Intercept any segment of the list
  • l[:]
?
1
2
3
4
#Subscript access list
l = [3,2,5,1,9,8,7]
 
print(l[1])

2

?
1
print(l[0])

3

?
1
2
3
4
5
6
7
8
#Slice operation
#Note that the intercepted range includes the subscript value on the left and does not include the subscript value on the right
print(l[1:4])
 
#The subscript value can be blank. If it is not written, the left subscript value is 0 by default, and the right subscript value is the maximum number plus one, which means that the last data is intercepted
print(l[:])
print(l[:4])
print(l[2:])

[2, 5, 1]
[3, 2, 5, 1, 9, 8, 7]
[3, 2, 5, 1]
[5, 1, 9, 8, 7]

?
1
2
3
4
5
6
7
8
9
10
11
12
13
print(l)
#Slice can control the growth range. The default growth range is 1
print(l[1:6:1])
 
#Print numbers starting with subscript 1, one at a time
print(l[1:6:2])
 
#The subscript can be out of range, and the redundant subscript content will not be considered after exceeding the range
print(l[2:10])
 
#Subscript value, the growth rate can be negative
#Is a negative number, indicating right to left
#Specification: the subscript of the last number of the array is - 1

[3, 2, 5, 1, 9, 8, 7]
[2, 5, 1, 9, 8]
[2, 1, 8]
[5, 1, 9, 8, 7]

?
1
2
3
4
5
6
7
8
9
10
11
#Negative subscript of slice
print(l)
 
#The following display is empty, because the default fragment is always intercepted from left to right
print(l[-2:-4])
print(l[-4:-2])
 
#If the value on the left is larger than that on the right, the step size parameter needs to use a negative number
#This case provides an idea for direct positive and negative interception of a list
print(l[-2:-4:-1])
print(l[-1:-8:-1])

[3, 2, 5, 1, 9, 8, 7]
[]
[1, 9]
[8, 9]
[7, 8, 9, 1, 5, 2, 3]

The slicing operation is to generate a new list

The built-in function ID is responsible for displaying the unique identification number of a variable or data

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#ID function example
a = 100
b = 200
print(id(a))
print(id(b))
 
#A and C point to the same data
c = a
print(id(c))
 
a = 101
print(a)
print(c)
 
print(id(a))
print(id(c))

140734817148832
140734817152032
140734817148832
101
100
140734817148864
140734817148832

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#Through the ID, you can directly judge whether the partition regenerates a piece of data or uses the same piece of data
l = [3,5,6,8,5,43,4,7]
ll = l[:]  #Slice operation
lll = ll
#If the two ID values are the same, it indicates that the list generated by fragmentation uses the same address and the same data
#Otherwise, it indicates that fragmentation regenerates a data, that is, a new list, and then copies the data to the new list
print(id(l))
print(id(ll))
print(id(lll))
 
#It is known from the ID that ll and LLL are the same data, and the verification code is as follows
l[1] = 100
print(l)
print(ll)
print(lll)
 
ll[1] = 100
print(ll)
print(lll)

1857540073800
1857540052488
1857540052488
[3, 100, 6, 8, 5, 43, 4, 7]
[3, 5, 6, 8, 5, 43, 4, 7]
[3, 5, 6, 8, 5, 43, 4, 7]
[3, 100, 6, 8, 5, 43, 4, 7]
[3, 100, 6, 8, 5, 43, 4, 7]

summary

This is the end of this article on Python variable scope and list. For more information about Python variable scope and list, please search for previous articles on developepper or continue to browse the relevant articles below. I hope you will support developepper in the future!

Recommended Today

Swift advanced (XV) extension

The extension in swift is somewhat similar to the category in OC Extension can beenumeration、structural morphology、class、agreementAdd new features□ you can add methods, calculation attributes, subscripts, (convenient) initializers, nested types, protocols, etc What extensions can’t do:□ original functions cannot be overwritten□ you cannot add storage attributes or add attribute observers to existing attributes□ cannot add parent […]