2018-12-12 2-10 Python基础-06-变量作用域和列表

第二章 语法基础

课时10 Python基础-06-变量作用域和列表

1.变量作用域

  • 全局变量:作用域为全局(global),在函数外部定义
  • 局部变量:作用域为局部(local),在函数内部定义
  • LEGB原则:
    L(local):局部作用域
    E(enclosing function locale):外部嵌套函数作用域
    G(global module):函数定义所在模块作用域
    B(buildin):Python内置模块的作用域
  • 举例

a) 不报错:函数内部调用函数外部的变量

#代码
a=1
def fun():
    print(a)
fun()
print(a)
#效果
1
1

b) 报错:函数内部重新给函数外部定义的变量赋值
报错原因:变量a为已定义的全局变量,不能在函数fun中定义或赋值

#代码
a=1
def fun():
    print(a)
    a=2
fun()
print(a)
#效果
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
 in ()
      3     print(a)
      4     a=2
----> 5 fun()
      6 print(a)

 in fun()
      1 a=1
      2 def fun():
----> 3     print(a)
      4     a=2
      5 fun()

UnboundLocalError: local variable 'a' referenced before assignment

c) 函数外部给函数内部定义的变量赋值(无法赋值,而是新建一个名称相同的全局变量)

#代码
def fun():
    a=1
    print(a)
    a=2
a=3
fun()
print(a)
fun() #本次调用函数时,被赋值的变量a为函数内部的变量,而不是给外部的全局变量赋值
#效果
1
3
1

?? 2.提升局部变量为全局变量

在函数内部定义全局变量:
*juoyter notebook中,一旦某一段函数使用了global p,那么在本文档中新建的函数代码都会将p作为全局变量来处理;此问题可以通过按下重启按钮进行恢复。

#代码
def fun():
    global a
    a = 1
fun() #必须进行调用,否则报错:a未定义
print(a)
#效果
1

3.globalslocals函数

由此可见local具有相对性!

#代码
a = 1
def fun(c):
    b = 2
    print("globals={0}".format(globals()))
    print("locals={0}".format(locals()))
fun(3)
print("locals={0}".format(locals()))
#效果
globals={'__name__': '__main__', '__doc__': 'Automatically created module for IPython interactive environment', '__package__': None, '__loader__': None, '__spec__': None, '__builtin__': , '__builtins__': , '_ih': ['', 'a=1\ndef fun():\n    print(a)\n    a=2\nprint(a)', 'a=1\ndef fun():\n    print(a)\n    a=2\nfun()\nprint(a)', 'a=1\ndef fun():\n    print(a)\nfun()\nprint(a)', 'a=1\ndef fun():\n    print(a)\n    a=2\nfun()\nprint(a)', 'def fun():\n    a=1\n    print(a)\na=2\nfun()\nprint(a)', 'def fun():\n    a=1\n    print(a)\na=2\nfun()\nprint(a)\nfun()', 'def fun():\n    a=1\n    print(a)\n    a=2\na=3\nfun()\nprint(a)\nfun()', 'def fun():\n    a=1\n    print(a)\na=3\nfun()\nprint(a)\nfun()', 'def fun():\n    a=1\n    print(a)\n    a=2\na=3\nfun()\nprint(a)\nfun()', 'def fun()\n    global a = 1\nprint(a)', 'def fun():\n    global a = 1\nprint(a)', 'def fun():\n    global a \n    a = 1\nprint(a)', 'def fun():\n    global n \n    n = 1\nprint(n)', 'def fun():\n    global n = 1\nprint(n)', 'a = 1\ndef fun(c):\n    b = 2\n    print(globals())\n    print(locals())\nfun(3)', 'a = 1\ndef fun(c):\n    b = 2\n    print("globals={0}".format(globals()))\n    print("locals={0}".format(locals()))\nfun(3)', 'a = 1\ndef fun(c):\n    b = 2\n    print("locals={0}".format(locals()))\nfun(3)\nprint("locals={0}".format(locals()))', 'a = 1\ndef fun(c):\n    b = 2\n    print("globals={0}".format(globals()))\n    print("locals={0}".format(locals()))\nfun(3)\nprint("locals={0}".format(locals()))'], '_oh': {}, '_dh': ['/home/tlxy/桌面'], 'In': ['', 'a=1\ndef fun():\n    print(a)\n    a=2\nprint(a)', 'a=1\ndef fun():\n    print(a)\n    a=2\nfun()\nprint(a)', 'a=1\ndef fun():\n    print(a)\nfun()\nprint(a)', 'a=1\ndef fun():\n    print(a)\n    a=2\nfun()\nprint(a)', 'def fun():\n    a=1\n    print(a)\na=2\nfun()\nprint(a)', 'def fun():\n    a=1\n    print(a)\na=2\nfun()\nprint(a)\nfun()', 'def fun():\n    a=1\n    print(a)\n    a=2\na=3\nfun()\nprint(a)\nfun()', 'def fun():\n    a=1\n    print(a)\na=3\nfun()\nprint(a)\nfun()', 'def fun():\n    a=1\n    print(a)\n    a=2\na=3\nfun()\nprint(a)\nfun()', 'def fun()\n    global a = 1\nprint(a)', 'def fun():\n    global a = 1\nprint(a)', 'def fun():\n    global a \n    a = 1\nprint(a)', 'def fun():\n    global n \n    n = 1\nprint(n)', 'def fun():\n    global n = 1\nprint(n)', 'a = 1\ndef fun(c):\n    b = 2\n    print(globals())\n    print(locals())\nfun(3)', 'a = 1\ndef fun(c):\n    b = 2\n    print("globals={0}".format(globals()))\n    print("locals={0}".format(locals()))\nfun(3)', 'a = 1\ndef fun(c):\n    b = 2\n    print("locals={0}".format(locals()))\nfun(3)\nprint("locals={0}".format(locals()))', 'a = 1\ndef fun(c):\n    b = 2\n    print("globals={0}".format(globals()))\n    print("locals={0}".format(locals()))\nfun(3)\nprint("locals={0}".format(locals()))'], 'Out': {}, 'get_ipython': >, 'exit': , 'quit': , '_': '', '__': '', '___': '', '_i': 'a = 1\ndef fun(c):\n    b = 2\n    print("locals={0}".format(locals()))\nfun(3)\nprint("locals={0}".format(locals()))', '_ii': 'a = 1\ndef fun(c):\n    b = 2\n    print("globals={0}".format(globals()))\n    print("locals={0}".format(locals()))\nfun(3)', '_iii': 'a = 1\ndef fun(c):\n    b = 2\n    print(globals())\n    print(locals())\nfun(3)', '_i1': 'a=1\ndef fun():\n    print(a)\n    a=2\nprint(a)', 'a': 1, 'fun': , '_i2': 'a=1\ndef fun():\n    print(a)\n    a=2\nfun()\nprint(a)', '_i3': 'a=1\ndef fun():\n    print(a)\nfun()\nprint(a)', '_i4': 'a=1\ndef fun():\n    print(a)\n    a=2\nfun()\nprint(a)', '_i5': 'def fun():\n    a=1\n    print(a)\na=2\nfun()\nprint(a)', '_i6': 'def fun():\n    a=1\n    print(a)\na=2\nfun()\nprint(a)\nfun()', '_i7': 'def fun():\n    a=1\n    print(a)\n    a=2\na=3\nfun()\nprint(a)\nfun()', '_i8': 'def fun():\n    a=1\n    print(a)\na=3\nfun()\nprint(a)\nfun()', '_i9': 'def fun():\n    a=1\n    print(a)\n    a=2\na=3\nfun()\nprint(a)\nfun()', '_i10': 'def fun()\n    global a = 1\nprint(a)', '_i11': 'def fun():\n    global a = 1\nprint(a)', '_i12': 'def fun():\n    global a \n    a = 1\nprint(a)', '_i13': 'def fun():\n    global n \n    n = 1\nprint(n)', '_i14': 'def fun():\n    global n = 1\nprint(n)', '_i15': 'a = 1\ndef fun(c):\n    b = 2\n    print(globals())\n    print(locals())\nfun(3)', '_i16': 'a = 1\ndef fun(c):\n    b = 2\n    print("globals={0}".format(globals()))\n    print("locals={0}".format(locals()))\nfun(3)', '_i17': 'a = 1\ndef fun(c):\n    b = 2\n    print("locals={0}".format(locals()))\nfun(3)\nprint("locals={0}".format(locals()))', '_i18': 'a = 1\ndef fun(c):\n    b = 2\n    print("globals={0}".format(globals()))\n    print("locals={0}".format(locals()))\nfun(3)\nprint("locals={0}".format(locals()))'}
locals={'b': 2, 'c': 3}
locals={'__name__': '__main__', '__doc__': 'Automatically created module for IPython interactive environment', '__package__': None, '__loader__': None, '__spec__': None, '__builtin__': , '__builtins__': , '_ih': ['', 'a=1\ndef fun():\n    print(a)\n    a=2\nprint(a)', 'a=1\ndef fun():\n    print(a)\n    a=2\nfun()\nprint(a)', 'a=1\ndef fun():\n    print(a)\nfun()\nprint(a)', 'a=1\ndef fun():\n    print(a)\n    a=2\nfun()\nprint(a)', 'def fun():\n    a=1\n    print(a)\na=2\nfun()\nprint(a)', 'def fun():\n    a=1\n    print(a)\na=2\nfun()\nprint(a)\nfun()', 'def fun():\n    a=1\n    print(a)\n    a=2\na=3\nfun()\nprint(a)\nfun()', 'def fun():\n    a=1\n    print(a)\na=3\nfun()\nprint(a)\nfun()', 'def fun():\n    a=1\n    print(a)\n    a=2\na=3\nfun()\nprint(a)\nfun()', 'def fun()\n    global a = 1\nprint(a)', 'def fun():\n    global a = 1\nprint(a)', 'def fun():\n    global a \n    a = 1\nprint(a)', 'def fun():\n    global n \n    n = 1\nprint(n)', 'def fun():\n    global n = 1\nprint(n)', 'a = 1\ndef fun(c):\n    b = 2\n    print(globals())\n    print(locals())\nfun(3)', 'a = 1\ndef fun(c):\n    b = 2\n    print("globals={0}".format(globals()))\n    print("locals={0}".format(locals()))\nfun(3)', 'a = 1\ndef fun(c):\n    b = 2\n    print("locals={0}".format(locals()))\nfun(3)\nprint("locals={0}".format(locals()))', 'a = 1\ndef fun(c):\n    b = 2\n    print("globals={0}".format(globals()))\n    print("locals={0}".format(locals()))\nfun(3)\nprint("locals={0}".format(locals()))'], '_oh': {}, '_dh': ['/home/tlxy/桌面'], 'In': ['', 'a=1\ndef fun():\n    print(a)\n    a=2\nprint(a)', 'a=1\ndef fun():\n    print(a)\n    a=2\nfun()\nprint(a)', 'a=1\ndef fun():\n    print(a)\nfun()\nprint(a)', 'a=1\ndef fun():\n    print(a)\n    a=2\nfun()\nprint(a)', 'def fun():\n    a=1\n    print(a)\na=2\nfun()\nprint(a)', 'def fun():\n    a=1\n    print(a)\na=2\nfun()\nprint(a)\nfun()', 'def fun():\n    a=1\n    print(a)\n    a=2\na=3\nfun()\nprint(a)\nfun()', 'def fun():\n    a=1\n    print(a)\na=3\nfun()\nprint(a)\nfun()', 'def fun():\n    a=1\n    print(a)\n    a=2\na=3\nfun()\nprint(a)\nfun()', 'def fun()\n    global a = 1\nprint(a)', 'def fun():\n    global a = 1\nprint(a)', 'def fun():\n    global a \n    a = 1\nprint(a)', 'def fun():\n    global n \n    n = 1\nprint(n)', 'def fun():\n    global n = 1\nprint(n)', 'a = 1\ndef fun(c):\n    b = 2\n    print(globals())\n    print(locals())\nfun(3)', 'a = 1\ndef fun(c):\n    b = 2\n    print("globals={0}".format(globals()))\n    print("locals={0}".format(locals()))\nfun(3)', 'a = 1\ndef fun(c):\n    b = 2\n    print("locals={0}".format(locals()))\nfun(3)\nprint("locals={0}".format(locals()))', 'a = 1\ndef fun(c):\n    b = 2\n    print("globals={0}".format(globals()))\n    print("locals={0}".format(locals()))\nfun(3)\nprint("locals={0}".format(locals()))'], 'Out': {}, 'get_ipython': >, 'exit': , 'quit': , '_': '', '__': '', '___': '', '_i': 'a = 1\ndef fun(c):\n    b = 2\n    print("locals={0}".format(locals()))\nfun(3)\nprint("locals={0}".format(locals()))', '_ii': 'a = 1\ndef fun(c):\n    b = 2\n    print("globals={0}".format(globals()))\n    print("locals={0}".format(locals()))\nfun(3)', '_iii': 'a = 1\ndef fun(c):\n    b = 2\n    print(globals())\n    print(locals())\nfun(3)', '_i1': 'a=1\ndef fun():\n    print(a)\n    a=2\nprint(a)', 'a': 1, 'fun': , '_i2': 'a=1\ndef fun():\n    print(a)\n    a=2\nfun()\nprint(a)', '_i3': 'a=1\ndef fun():\n    print(a)\nfun()\nprint(a)', '_i4': 'a=1\ndef fun():\n    print(a)\n    a=2\nfun()\nprint(a)', '_i5': 'def fun():\n    a=1\n    print(a)\na=2\nfun()\nprint(a)', '_i6': 'def fun():\n    a=1\n    print(a)\na=2\nfun()\nprint(a)\nfun()', '_i7': 'def fun():\n    a=1\n    print(a)\n    a=2\na=3\nfun()\nprint(a)\nfun()', '_i8': 'def fun():\n    a=1\n    print(a)\na=3\nfun()\nprint(a)\nfun()', '_i9': 'def fun():\n    a=1\n    print(a)\n    a=2\na=3\nfun()\nprint(a)\nfun()', '_i10': 'def fun()\n    global a = 1\nprint(a)', '_i11': 'def fun():\n    global a = 1\nprint(a)', '_i12': 'def fun():\n    global a \n    a = 1\nprint(a)', '_i13': 'def fun():\n    global n \n    n = 1\nprint(n)', '_i14': 'def fun():\n    global n = 1\nprint(n)', '_i15': 'a = 1\ndef fun(c):\n    b = 2\n    print(globals())\n    print(locals())\nfun(3)', '_i16': 'a = 1\ndef fun(c):\n    b = 2\n    print("globals={0}".format(globals()))\n    print("locals={0}".format(locals()))\nfun(3)', '_i17': 'a = 1\ndef fun(c):\n    b = 2\n    print("locals={0}".format(locals()))\nfun(3)\nprint("locals={0}".format(locals()))', '_i18': 'a = 1\ndef fun(c):\n    b = 2\n    print("globals={0}".format(globals()))\n    print("locals={0}".format(locals()))\nfun(3)\nprint("locals={0}".format(locals()))'}

4.evalexec函数:把字符串当做代码来执行(神器!)

eval("string_code",global=None,local=None)

#代码
x = 1
y = 2
z1 = eval("x + y")
z2 = eval("x + y")
print(z1)
print(z2)
#效果
3
None

5.递归函数:定义一个函数,在内部调用之(调用自己)

注意:Python中队递归深度限制约1965层,超出报错
一定要写结束条件

#代码
a = 0
def fun():
    global a
    a += 1
    print(a)
    fun()
fun()
#效果
1
2
... #太多了,省略中间一千多行
1964
1965
---------------------------------------------------------------------------
RecursionError                            Traceback (most recent call last)
 in ()
      5     print(a)
      6     fun()
----> 7 fun()

 in fun()
      4     a += 1
      5     print(a)
----> 6     fun()
      7 fun()

... last 1 frames repeated, from the frame below ...

 in fun()
      4     a += 1
      5     print(a)
----> 6     fun()
      7 fun()

RecursionError: maximum recursion depth exceeded in comparison

a) 斐波那契数列
f(1) = 1,f(2) = 2,f(n) = f(n-2) + f(n-1)

#代码
def fib(n):
    if n <= 0 or n%1 != 0:
        return "请输入大于等于1的整数"
    elif n == 1 or n == 2: #不可以写成“if n == 1 or 2:”
        return 1
    else:
        return fib(n-2) + fib(n-1)
print(fib(-1))
print(fib(1))
print(fib(3))
#效果
请输入大于等于1的整数
1
2

数字不能过大,否则超出计算机计算能力,建议设置n在20以内

6.内置数据结构(变量类型)

  • list 列表(有先后顺序,元素可重复)
    创建空列表:list1 = []
    创建单元素列表:list2 = [100]
    创建多元素列表:list3 = [1,2,3]
    其他语法:list4 = list() #括号内至多1个参数,且不为数值类型

a) 访问列表中的单个元素:使用下标操作(索引),下标都是从0开始!!!

#代码
l = [2,141,2,32,34,1]
print(l[3])
#效果
32

b) 访问列表中的连续多个元素(分片
注意:l[a:b]表示从ab-1!!!
a小于0,表示从右往左数,最右数的下标值为-1,如图所示:

#代码
l = [0,141,9,32,34,1]
print(l[2:4])
print(l[2:])
print(l[:4])
print(l[:])
print(l[1:4:1])
print(l[1:4:2])
print(l[-4:-2])
print(l[-2:-4]) #切片默认从左往右切
print(l[-2:-4:-1]) 
#效果
[9, 32]
[9, 32, 34, 1]
[0, 141, 9, 32]
[0, 141, 9, 32, 34, 1]
[141, 9, 32]
[141, 32]
[9, 32]
[]
[34, 32]
  • set
  • dict
  • tuple
  • etc) id函数:显示某个变量或数据的唯一确定的编号
#代码
a = 1
print(id(a))
b = 2
print(id(b))
a = 3 #对a赋新值
print(id(a))
c = a #将a复制给c
print(id(c))
a = 4
print(id(a))
#效果
94112357272800
94112357272832
94112357272864 #对a赋新值
94112357272864 #将a复制给c
94112357272896 #再次对a赋新值

你可能感兴趣的:(2018-12-12 2-10 Python基础-06-变量作用域和列表)