全局变量是在函数外部定义和声明的变量,我们需要在函数内部使用它们。
# This function uses global variable s
def
f():
print
s
# Global scope
s =
"I love Geeksforgeeks"
f()
输出:
我喜欢Geeksforgeeks
如果在函数范围内定义了具有相同名称的变量,那么它将仅打印函数内给出的值而不是全局值。
# This function has a variable with
# name same as s.
def
f():
s =
"Me too."
print
s
# Global scope
s =
"I love Geeksforgeeks"
f()
print
s
复制代码在IDE上运行
输出:
我也是。
我喜欢Geeksforgeeks。
在我们调用函数f()之前,变量s被定义为字符串“I love Geeksforgeeks”。f()中唯一的语句是“print s”语句。由于没有本地s,将使用全局s的值。
问题是,如果我们改变函数f()中s的值,会发生什么?它也会影响全球吗?我们在下面的代码中测试它:
def
f():
print
s
# This program will NOT show error
# if we comment below line.
s =
"Me too."
print
s
# Global scope
s =
"I love Geeksforgeeks"
f()
print
s
输出:
第2行:undefined:错误:赋值前引用的局部变量's'
为了使上述程序有效,我们需要使用“global”关键字。如果我们想要分配/更改它们,我们只需要在函数中使用全局关键字。打印和访问不需要全局。为什么?Python“假设”我们想要一个局部变量,因为在f()内部赋值,所以第一个print语句抛出此错误消息。在函数内部更改或创建的任何变量都是本地的,如果它尚未声明为全局变量。要告诉Python,我们要使用全局变量,我们必须使用关键字“global”,如以下示例所示:
# This function modifies global variable 's'
def
f():
global
s
print
s
s =
"Look for Geeksforgeeks Python Section"
print
s
# Global Scope
s =
"Python is great!"
f()
print
s
现在没有歧义。
输出:
Python太棒了!
寻找Geeksforgeeks Python部分。
寻找Geeksforgeeks Python部分。
一个很好的例子
a =
1
# Uses global because there is no local 'a'
def
f():
print
'Inside f() : ', a
# Variable 'a' is redefined as a local
def
g():
a =
2
print
'Inside g() : ',a
# Uses global keyword to modify global 'a'
def
h():
global
a
a =
3
print
'Inside h() : ',a
# Global scope
print
'global : ',a
f()
print
'global : ',a
g()
print
'global : ',a
h()
print
'global : ',a
输出:
global:1
inside f():1
global:1
inside g():2
global:1
inside h():3
global:3








暂无数据