在这篇文章中,你将学习全局变量的基本知识。
首先,你将学习如何在 Python 中声明变量,以及术语 "变量范围 "的实际含义。
然后,你将学习局部变量和全局变量之间的区别,了解如何定义全局变量以及如何使用global 关键字。
下面是我们要讲的内容:
什么是Python中的变量以及如何创建它们?初学者的介绍
你可以把变量看成是存储容器。
它们是存放数据、信息和你想保存在计算机内存中的值的存储容器。然后,你可以在程序的整个生命周期中的某个时刻引用甚至操作它们。
一个变量有一个符号化的名字,你可以把这个名字看作是存储容器上的标签,作为它的标识符。
变量名称将是对存储在它里面的数据的引用和指针。所以,不需要记住你的数据和信息的细节--你只需要引用保存这些数据和信息的变量名称。
当给一个变量起名时,要确保它能描述它所持有的数据。变量名称需要清晰,并且容易理解,无论是对你未来的自己还是你可能与之合作的其他开发者。
现在,让我们看看如何在 Python 中实际创建一个变量。
在 Python 中声明变量时,你不需要指定它们的数据类型。
例如,在C编程语言中,你必须明确提到变量将容纳的数据类型。
所以,如果你想存储你的年龄,这是一个整数,或者int ,这是你在C语言中必须做的。
#include <stdio.h>
int main(void)
{
int age = 28;
// 'int' is the data type
// 'age' is the name
// 'age' is capable of holding integer values
// positive/negative whole numbers or 0
// '=' is the assignment operator
// '28' is the value
}
然而,你在Python中是这样写上述内容的:
age = 28
#'age' is the variable name, or identifier
# '=' is the assignment operator
#'28' is the value assigned to the variable, so '28' is the value of 'age'
变量名总是在左边,而你要分配的值在分配运算符之后的右边。
请记住,你可以在程序的整个生命周期内改变变量的值。
my_age = 28
print(f"My age in 2022 is {my_age}.")
my_age = 29
print(f"My age in 2023 will be {my_age}.")
#output
#My age in 2022 is 28.
#My age in 2023 will be 29.
你保持相同的变量名称,my_age ,但只是将其值从28 改为29 。
Python中的变量范围是什么意思?
变量范围指的是Python程序中变量可用、可访问和可见的部分和边界。
Python 变量有四种范围,也被称为LEGB 规则:
- 本地
- 包围的
- 全局
- 内置
在本文的其余部分,你将重点学习用全局范围创建变量,你将了解局部和全局变量范围的区别。
如何在Python中用局部范围创建变量
在一个函数体内定义的变量具有局部作用域,这意味着它们只能在那个特定的函数内访问。换句话说,它们是该函数的 "局部"。
你只能通过调用该函数来访问一个局部变量:
def learn_to_code():
#create local variable
coding_website = "freeCodeCamp"
print(f"The best place to learn to code is with {coding_website}!")
#call function
learn_to_code()
#output
#The best place to learn to code is with freeCodeCamp!
看看当我试图从函数主体之外访问那个具有局部作用域的变量时会发生什么:
def learn_to_code():
#create local variable
coding_website = "freeCodeCamp"
print(f"The best place to learn to code is with {coding_website}!")
#try to print local variable 'coding_website' from outside the function
print(coding_website)
#output
#NameError: name 'coding_website' is not defined
它引发了一个NameError ,因为它在程序的其他部分是不 "可见 "的。它只在定义它的函数中是 "可见 "的。
如何在 Python 中创建具有全局范围的变量
当你在一个函数之外定义一个变量时,比如在文件的顶部,它有一个全局范围,被称为全局变量。
一个全局变量可以从程序的任何地方被访问。
你可以在函数体内使用它,也可以从函数外访问它:
#create a global variable
coding_website = "freeCodeCamp"
def learn_to_code():
#access the variable 'coding_website' inside the function
print(f"The best place to learn to code is with {coding_website}!")
#call the function
learn_to_code()
#access the variable 'coding_website' from outside the function
print(coding_website)
#output
#The best place to learn to code is with freeCodeCamp!
#freeCodeCamp
如果有一个全局变量和一个局部变量,并且它们都有相同的名字,会发生什么?
#global variable
city = "Athens"
def travel_plans():
#local variable with the same name as the global variable
city = "London"
print(f"I want to visit {city} next year!")
#call function - this will output the value of local variable
travel_plans()
#reference global variable - this will output the value of global variable
print(f"I want to visit {city} next year!")
#output
#I want to visit London next year!
#I want to visit Athens next year!
在上面的例子中,也许你并不期望有这种特定的输出。
也许你认为当我在函数中给它分配了一个不同的值时,city 的值会改变。
也许你以为当我用print(f" I want to visit {city} next year!") 行引用全局变量时,输出会是#I want to visit London next year! ,而不是#I want to visit Athens next year! 。
然而,当函数被调用时,它打印的是局部变量的值。
然后,当我在函数外引用全局变量时,分配给全局变量的值被打印出来。
它们并没有相互干扰。
也就是说,为全局变量和局部变量使用相同的变量名并不被认为是一种最佳做法。确保你的变量没有相同的名字,因为当你运行你的程序时,你可能会得到一些混乱的结果。
如何在 Python 中使用global 关键字
如果你有一个全局变量,但想在一个函数中改变它的值,怎么办?
看看当我试图这样做时会发生什么:
#global variable
city = "Athens"
def travel_plans():
#First, this is like when I tried to access the global variable defined outside the function.
# This works fine on its own, as you saw earlier on.
print(f"I want to visit {city} next year!")
#However, when I then try to re-assign a different value to the global variable 'city' from inside the function,
#after trying to print it,
#it will throw an error
city = "London"
print(f"I want to visit {city} next year!")
#call function
travel_plans()
#output
#UnboundLocalError: local variable 'city' referenced before assignment
默认情况下,Python 认为你想在一个函数中使用一个局部变量。
所以,当我首先尝试打印变量的值,然后为我试图访问的变量重新赋值时,Python 会感到困惑。
在一个函数中改变全局变量值的方法是使用global 关键字:
#global variable
city = "Athens"
#print value of global variable
print(f"I want to visit {city} next year!")
def travel_plans():
global city
#print initial value of global variable
print(f"I want to visit {city} next year!")
#assign a different value to global variable from within function
city = "London"
#print new value
print(f"I want to visit {city} next year!")
#call function
travel_plans()
#print value of global variable
print(f"I want to visit {city} next year!")
在函数中引用它之前使用global 关键字,因为你会得到以下错误:SyntaxError: name 'city' is used prior to global declaration 。
早些时候,你看到你不能访问在函数内创建的变量,因为它们有局部范围。
global 关键字改变了函数内部声明的变量的可见性:
def learn_to_code():
global coding_website
coding_website = "freeCodeCamp"
print(f"The best place to learn to code is with {coding_website}!")
#call function
learn_to_code()
#access variable from within the function
print(coding_website)
#output
#The best place to learn to code is with freeCodeCamp!
#freeCodeCamp
结论
这就是你的收获!你现在知道了 Python 中全局变量的基本知识,并且能够分辨出局部变量和全局变量之间的区别。
我希望你觉得这篇文章很有用。
要学习更多关于Python编程语言的知识,请查看freeCodeCamp的Python科学计算认证。
你将从基础知识开始,以一种互动的、适合初学者的方式学习。你还会在最后建立五个项目,将其付诸实践,帮助巩固你所学的知识。
谢谢你的阅读,祝你编码愉快