• 06-局部变量和全局变量


    局部变量:在函数内部定义的变量,只是在当前函数中使用,在其他函数就不行

    In [1]: def test1():    #定义一个test1函数
       ...:     a = 100  #赋值
       ...:     
    
    In [2]: def test2():    #定义一个test2函数
       ...:     print("a=%d"%a)  #打印
       ...:     
    In [4]: test1()  #调用test1函数,因为没有return,所以结果为空
    
    In [5]: test2()  #调用test2函数,报错
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-5-35ebc1c532fc> in <module>()
    ----> 1 test2()
    
    <ipython-input-2-d9ea9e4cdd20> in test2()
          1 def test2():
    ----> 2     print("a=%d"%a)
          3 
    
    NameError: name 'a' is not defined  #表示a没有定义,a是在test1函数中定义的局部变量

    全局变量:在函数外定义,在任何函数里都能使用

    In [1]: a = 99    #在函数外定义的变量,在任何函数中都能使用
    
    In [2]: def test1():
       ...:     a = 100
       ...:     print("test1函数中a=%d"%a)
       ...:     
    
    In [3]: def test2():
       ...:     print("test2函数中a=%d"%a)
       ...:     
    
    In [4]: test1()
    test1函数中a=100
    
    In [5]: test2()
    test2函数中a=99

    为什么打印test1函数中a的值会是100呢?因为在程序运行时,开始调用函数,会先寻找局部变量,如果没有再去找全局变量

    global  #声明全局变量

    root@ubuntu:/home/python/codes/python基础-05# cat !$
    cat 03-获取温度.py
    wendu = 30  #定义了一个全局变量wendu
    def get_wendu():
        wendu = 33  #对wendu进行修改
    
    def print_wendu():
        print("此时的温度是%d"%wendu)  #打印
    
    
    get_wendu()  #调用函数
    print_wendu()  #调用函数
    
    root@ubuntu:/home/python/codes/python基础-05# python3 !$
    python3 03-获取温度.py
    此时的温度是30  #结果为30

    为什么会这样呢,明明在函数中对wendu这个全局变量进行修改了,可结果还是30呢?因为如果wendu这个变量已经在全局变量的位置定义了,此时还想在函数中对这个全局变量进行修改的话,那么wendu=一个值这还不够,此时wendu这个变量是一个局部变量,仅仅是和全局变量的名字一样,修改结果如下:

    root@ubuntu:/home/python/codes/python基础-05# cat !$
    cat 03-获取温度.py
    wendu = 30
    def get_wendu():
        global wendu  #global wendu用来对一个全局变量的声明,那么wendu=33就是对全局变量的修改
        wendu = 33
    
    def print_wendu():
        print("此时的温度是%d"%wendu)
    
    
    get_wendu()
    print_wendu()
    
    root@ubuntu:/home/python/codes/python基础-05# python3 !$
    python3 03-获取温度.py
    此时的温度是33

    当局部变量和全局变量名字一样时,会选择局部变量,默认是定义,global是修改

    全局变量定义的位置

    1.把一个变量放在定义函数的前面***

    2.调用函数之前

    函数的文档说明

    让我们先来看一下我们自己定义的函数:

    In [1]: def test():
       ...:     print("abcdefg")
       ...:     
    
    In [2]: help(test)
    
    Help on function test in module __main__:
    
    test()

    什么都没有说明,我们今天写的代码可能今天知道,但是过了很久就忘记了,那么需要怎么解决呢,我们需要对函数进行文档说明,让我们再看一下内置函数:

    In [3]: help(print)
    
    Help on built-in function print in module builtins:
    
    print(...)
        print(value, ..., sep=' ', end='
    ', file=sys.stdout, flush=False)
        
        Prints the values to a stream, or to sys.stdout by default.
        Optional keyword arguments:
        file:  a file-like object (stream); defaults to the current sys.stdout.
        sep:   string inserted between values, default a space.
        end:   string appended after the last value, default a newline.
        flush: whether to forcibly flush the stream.

    看到了吧,print有着文档说明,那么让我们给test函数添加文档说明:

    In [4]: def test():
       ...:     '''打印字符串'''    #这就告诫我们一定要养成写注释的好习惯
       ...:     print("abcdef")
       ...:     
    
    In [5]: help(test)
    
    Help on function test in module __main__:
    
    test()
        打印字符串

    列表、字典当做全局变量

    如果列表作为全局变量,可以直接用,不需要添加global,因为在python当中,列表和字典是可变类型的

    root@ubuntu:/home/python/codes/python基础-05# cat test.py 
    #-*- coding:utf-8 -*-
    nums = [11,22,33]
    infor = {"name":"laowang","age":16}
    
    def test1():
        nums.append(44)
        infor['addr']= "henan"
    def test2():
        print(nums)
        print(infor)
    
    test1()
    test2()
    
    root@ubuntu:/home/python/codes/python基础-05# python3 test.py 
    [11, 22, 33, 44]
    {'addr': 'henan', 'age': 16, 'name': 'laowang'}
  • 相关阅读:
    富士康前端一面
    中孚前端面筋
    至真科技校招前端面筋
    SysFader:iexplore.exe错误
    设置文件属性
    SQL2000数据库定期自动备份与修改
    如何配置jdk1.5的环境变量及运行java程序
    ResultSet的getDate()、getTime()和getTimestamp()比较
    Java BigDecimal详解
    MVVM教程(一):MVVM简介与准备工作
  • 原文地址:https://www.cnblogs.com/xiaoyafei/p/8555543.html
Copyright © 2020-2023  润新知