Python中的全局和局部变量

全局变量 是指未在任何函数中定义且具有全局范围的函数 局部变量 是在函数内部定义的,其范围仅限于该函数。换句话说,我们可以说局部变量只能在初始化它的函数内部访问,而全局变量可以在整个程序和每个函数内部访问。

null

局部变量

局部变量是在函数内部初始化的变量,只属于该特定函数。它不能在函数之外的任何地方访问。让我们看看如何创建局部变量。

例子: 创建局部变量

Python3

def f():
# local variable
s = "I love Geeksforgeeks"
print (s)
# Driver code
f()


输出

I love Geeksforgeeks

如果我们尝试在函数之外使用这个局部变量,那么让我们看看会发生什么。

例子:

Python3

def f():
# local variable
s = "I love Geeksforgeeks"
print ( "Inside Function:" , s)
# Driver code
f()
print (s)


输出

NameError: name 's' is not defined

全局变量

全局变量是在任何函数外部定义的,并且在整个程序中都可以访问的变量,即在每个函数内部和外部。让我们看看如何创建全局变量。

例子: 定义和访问全局变量

Python3

# This function uses global variable s
def f():
print ( "Inside Function" , s)
# Global scope
s = "I love Geeksforgeeks"
f()
print ( "Outside Function" , s)


输出

Inside Function I love GeeksforgeeksOutside Function I love Geeksforgeeks

变量s被定义为全局变量,在函数内部和外部都使用。

注: 由于没有局部变量,因此将使用全局变量的值。

现在,如果函数内部以及全局初始化了一个同名变量,该怎么办。现在问题来了,局部变量会对全局变量产生一些影响吗?反之亦然。如果我们改变函数f()中变量的值,会发生什么?它也会影响全球吗?我们在下面的代码中测试它:

Python3

# 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)


输出:

Me too.I love Geeksforgeeks.

如果在函数范围内也定义了同名变量,那么它将只打印函数内给定的值,而不打印全局值。

问题是,如果我们试图改变函数中全局变量的值会怎样。让我们看看下面的例子。

例子:

Python3

# This function uses global variable s
def f():
s + = 'GFG'
print ( "Inside Function" , s)
# Global scope
s = "I love Geeksforgeeks"
f()


输出

UnboundLocalError: local variable 's' referenced before assignment

为了使上述程序正常工作,我们需要使用“global”关键字。让我们看看这个全局关键字是什么。

全局关键字

我们只需要使用 全局关键字 在函数中,如果我们想进行赋值或更改全局变量。打印和访问不需要global。Python“假定”由于f()内部的s赋值,我们需要一个局部变量,因此第一条语句抛出错误消息。在函数内部更改或创建的任何变量,如果没有声明为全局变量,都是局部变量。为了告诉Python我们想要使用全局变量,我们必须使用关键字 “全球” ,如下例所示:

例1: 使用全局关键字

Python3

# This function modifies the global variable 's'
def f():
global s
s + = ' GFG'
print (s)
s = "Look for Geeksforgeeks Python Section"
print (s)
# Global Scope
s = "Python is great!"
f()
print (s)


输出

Python is great! GFGLook for Geeksforgeeks Python SectionLook for Geeksforgeeks Python Section

现在已经没有歧义了。

例2: 使用全局和局部变量

Python3

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 :  1Inside f() :  1global :  1Inside g() :  2global :  1Inside h() :  3global :  3

本文由 Shwetanshu Rohatgi .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享