Python中的全局变量和局部变量

2021年3月11日17:08:20 发表评论 787 次浏览

全局变量是在函数外部定义和声明的变量, 我们需要在函数内部使用它们。

# This function uses global variable s
def f(): 
     print (s) 
  
# Global scope
s = "I love lsbin"
f()

输出如下:

I love lsbin

在调用函数f()之前, 将变量s定义为字符串" I love lsbin"。 f()中唯一的语句是" print s"语句。由于没有local, 因此将使用global的值。

# This function has a variable with
# name same as s.
def f(): 
     s = "Me too."
     print (s)
  
# Global scope
s = "I love lsbin" 
f()
print (s)

输出如下:

Me too.
I love lsbin.

如果在函数范围内也定义了具有相同名称的变量, 则它将仅打印函数内部给定的值, 而不输出全局值。

问题是, 如果我们在函数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 lsbin" 
f()
print (s)

输出如下:

Line 2: undefined: Error: local variable 's' referenced before assignment

为了使上述程序有效, 我们需要使用" global"关键字。如果我们要进行分配/更改它们, 则只需要在函数中使用global关键字即可。全局不需要打印和访问。为什么? Python"假定"由于要在f()内部分配s而需要局部变量, 因此第一个print语句会抛出此错误消息。如果尚未在函数内部更改或创建的任何变量未声明为全局变量, 则该变量为本地变量。要告诉Python我们要使用全局变量, 我们必须使用关键字"全球", 如以下示例所示:

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

现在没有歧义了。

输出如下:

Python is great!
Look for lsbin Python Section.
Look for lsbin Python Section.

一个很好的例子

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

如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。

注意怪胎!巩固你的基础Python编程基础课程和学习基础知识。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: