博客
关于我
06-局部变量和全局变量
阅读量:595 次
发布时间:2019-03-11

本文共 3189 字,大约阅读时间需要 10 分钟。

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

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)
in
()----> 1 test2()
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=100In [5]: test2()test2函数中a=99

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

global  #声明全局变量

root@ubuntu:/home/python/codes/python基础-05# cat !$cat 03-获取温度.pywendu = 30  #定义了一个全局变量wendudef 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-获取温度.pywendu = 30def get_wendu():    global wendu  #global wendu用来对一个全局变量的声明,那么wendu=33就是对全局变量的修改    wendu = 33def 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='\n', 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'}

 

转载地址:http://kpltz.baihongyu.com/

你可能感兴趣的文章
NetworkX:是否为每个节点添加超链接?
查看>>
network小学习
查看>>
Netwox网络工具使用详解
查看>>
Net与Flex入门
查看>>
Net任意String格式转换为DateTime类型
查看>>
net包之IPConn
查看>>
net发布的dll方法和类显示注释信息(字段说明信息)[图解]
查看>>
Net和T-sql中的日期函数操作
查看>>
Net处理html页面元素工具类(HtmlAgilityPack.dll)的使用
查看>>
Net操作Excel(终极方法NPOI)
查看>>
Net操作配置文件(Web.config|App.config)通用类
查看>>
net网络查看其参数state_dict,data,named_parameters
查看>>
Net连接mysql的公共Helper类MySqlHelper.cs带MySql.Data.dll下载
查看>>
NeurIPS(神经信息处理系统大会)-ChatGPT4o作答
查看>>
neuroph轻量级神经网络框架
查看>>
Neutron系列 : Neutron OVS OpenFlow 流表 和 L2 Population(7)
查看>>
new Blob()实现不同类型的文件下载功能
查看>>
New Concept English three (35)
查看>>
NEW DATE()之参数传递
查看>>
New Journey--工作五年所思所感小记
查看>>