Home > Backend Development > Python Tutorial > Detailed explanation of Python global variables and local variables

Detailed explanation of Python global variables and local variables

高洛峰
Release: 2016-10-19 15:20:17
Original
1299 people have browsed it

Detailed explanation of Python global variables and local variables

#Python中的变量:全局变量和局部变量
  
#在很多语言中,在声明全局变量的时候,都喜欢把全局变量的名称定义为大写
  
#定义学生人数为100
STUDENT_NUMBER = 100
#学校名称
SCHOOL_NAME = 'Guangzhou University'
  
"""\
    获取全局变量:学生人数STUDENT_NUMBER的值
"""
def getStudentNumber():
    return STUDENT_NUMBER
"""\
    重置全局变量:学生人数STUDENT_NUMBER值
"""
def setStudentNumber(num):
    global STUDENT_NUMBER
    STUDENT_NUMBER = num
"""\
    获取全局变量:学校名称SCHOOL_NAME的值
"""
def getSchoolName():
    return SCHOOL_NAME
"""\
    重置全局变量:学校名称SCHOOL_NAME值
"""
def setSchoolName(name):
    global SCHOOL_NAME
    SCHOOL_NAME = name
  
def changeValue():
    name = '北京大学'
    number = 90
    print('全局变量STUDENT_NUMBER = ' , getStudentNumber())
    print('全局变量SCHOOL_NAME = ' , getSchoolName())
    print('#######################################')
    print('局部变量namber = ' , number)
    print('局部变量name = ' , name)
    print('#######################################')
    print('改变全局变量值...')
    print('#######################################')
    setStudentNumber(number)
    setSchoolName(name)
    print('全局变量STUDENT_NUMBER = ' , getStudentNumber())
    print('全局变量SCHOOL_NAME = ' , getSchoolName())
  
if __name__ == '__main__':
    changeValue()
Copy after login


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template