python 全局
Python全局关键字 (Python global keyword)
global is a keyword (case-sensitive) in python, it is used to declare a global variable inside a function (from a non-global scope).
global是python中的一个关键字(区分大小写),用于在函数内部声明一个全局变量(来自非全局范围)。
As we know that variables are accessible within the same scope in which they are declared but a global variable can be accessed within a program anywhere. In python, we can define a global variable inside a function or in a non-global using by using global keyword.
众所周知,在声明变量的相同范围内可以访问变量,但是可以在程序中的任何位置访问全局变量 。 在python中,我们可以通过使用global关键字定义函数内部或非全局变量中的全局变量。
Syntax of global keyword
全局关键字的语法
global variable_name
Note: Before accessing the global variable outside of the function, function in which global variable is declared must be called.
注意:在访问函数外部的全局变量之前,必须先调用声明了全局变量的函数。
Example:
例:
# function
def myfunc():
# global variable
global a
# assigning the value to a
a = 10
# main code
# function call
myfunc()
print("outside the function a: ", a)
Output:
outside the function a: 10
最终关键字的Python示例 (Python examples of finally keyword)
Example 1: Declare a global variable inside a function, assign the value after the declaration, and print the value inside and outside of the function.
示例1:在函数内部声明一个全局变量,在声明之后分配值,并在函数内部和外部打印该值。
# python code to demonstrate example of
# gloabl keyword
# function
def myfunc():
# global variable
global a
# assigning the value to a
a = 10
# printing the value
print("inside myfunc() a: ", a)
# main code
# function call
myfunc()
print("outside the function a: ", a)
Output
输出量
inside myfunc() a: 10
outside the function a: 10
翻译自: https://www.includehelp.com/python/global-keyword-with-example.aspx
python 全局