zoukankan      html  css  js  c++  java
  • Python函数(三)-局部变量

    • 全局变量

    全局变量在函数中能直接访问

    # -*- coding:utf-8 -*-
    __author__ = "MuT6 Sch01aR"
    
    name = 'John'
    
    def test():
        print(name)
    
    test()
    

    运行结果

    但是全局变量的值(数字,字符串)不会被函数修改

    # -*- coding:utf-8 -*-
    __author__ = "MuT6 Sch01aR"
    
    name = 'John'
    
    def test(name):
        print("before change",name)
        name = 'Jack'
        print("after change",name)
    
    test(name)
    print(name)
    

    运行结果

    name变量在函数内被修改过,只在函数内有效,不影响全局变量的值,最后打印的全局变量的值还是不变

    函数可以修改全局变量定义的列表,字典,集合

    # -*- coding:utf-8 -*-
    __author__ = "MuT6 Sch01aR"
    
    list_1 = ['Python','php','java']
    dict_1 = {'name':'John','age':22}
    set_1 = {'Chinese','Art','Math'}
    
    def change():
        list_1[1] = 'asp'
        dict_1['name'] = 'Jack'
        set_1.pop() #随机删除一个值
        print(list_1)
        print(dict_1)
        print(set_1)
    
    print(list_1)
    print(dict_1)
    print(set_1)
    print("----------------+---------------")
    change()
    print("--------------After-Change--------------")
    print(list_1)
    print(dict_1)
    print(set_1)
    

    运行结果

    全局变量里的列表,字典,集合都在函数内被修改了

    • 局部变量

    局部变量就是在函数内定义的变量

    直接定义一个局部变量

    # -*- coding:utf-8 -*-
    __author__ = "MuT6 Sch01aR"
    
    def test():
        name = 'John'
        print(name)
    
    test()
    print(name)
    

    运行结果

    函数内的局部变量函数外部访问不了,只能在函数内部调用

    如果想让局部变量跟全局变量一样可以全局调用,需要用global关键字

    # -*- coding:utf-8 -*-
    __author__ = "MuT6 Sch01aR"
    
    def test():
        global name #把局部变量name设置为全局变量
        name = 'John'
        print(name)
    
    test()
    print(name)
    

    运行结果

    函数外也能访问到函数内定义的变量了

  • 相关阅读:
    黑马程序员——正则表达式
    黑马程序员——集合框架知识点总结
    黑马程序员——String类知识点详细
    黑马程序员——System、Runtime、Date、Calender、Math静态类
    黑马程序员——IO流总结
    黑马程序员——多线程中的安全问题 :
    获取一段字符串中含有某一子字符串的个数的方法定义:
    debian彻底删除apache2
    linux下mysql的安装
    markdown学习
  • 原文地址:https://www.cnblogs.com/sch01ar/p/8395176.html
Copyright © 2011-2022 走看看