python中的全局局部和非局部变量

First of all, I’m not the one on that image above. I’m just a benevolent writer who is here to talk about one of the most confusing concepts in Python programming “Global, Local and Nonlocal variables”. I know after reading the title you will be like “Why should I even worry about this”. Well, the answer is sometimes not knowing these teeny tiny itsy bitsy would cost you a lot. So without further ado, let’s get started.

开始步骤的是,我不是上面的图像上的人。 我只是一个仁慈的作家,他在这里谈论Python编程中最令人困惑的概念之一“ 全局,局部和非局部变量 ”。 我知道阅读标题后,您会像“ 我为什么还要为此担心 ”。 好吧,答案有时就是不知道这些很小的小东西会花很多钱。 因此,事不宜迟,让我们开始吧。

In programming languages like C/C++, every time a variable is declared simultaneously a memory would be allocated this would allocation would completely depend on the variable type. Therefore, the programmers must specify the variable type while creating a variable. But luckily in Python, you don’t have to do that. Python doesn’t have a variable type declaration. Like pointers in C, variables in Python don’t store values legitimately; they work with references highlighting objects in memory.

在像C / C ++这样的编程语言中,每次同时声明一个变量时,都会分配一个内存,而分配将完全取决于变量类型。 因此,程序员在创建变量时必须指定变量类型。 但是幸运的是,在Python中,您不必这样做。 Python没有变量类型声明。 像C中的指针一样,Python中的变量不会合法地存储值。 它们与突出显示内存中对象的引用一起使用。

主题 (Topics)

The list of topics that would be covered in this article is given below:

下面列出了本文将涉及的主题列表:

  • Variables — A quick introduction

    变量 -快速介绍

  • Global Variables — How to get rid of UnboundLocalError

    全局变量 —如何摆脱UnboundLocalError

  • Local Variables — How to get rid of NameError

    局部变量 —如何摆脱NameError

  • Nonlocal Variables — When and how to use them

    非局部变量 -何时以及如何使用它们

Also, before getting started I have to tell you one thing. The whole code of this article can be found in my GitHub Repository given below:

另外,在开始之前,我必须告诉您一件事。 可以在下面给出的GitHub存储库中找到本文的完整代码:

变数 (Variables)

A variable is more likely a container to store the values. Now the values to be stored depends on the programmer whether to use integer, float, string or etc.

变量更可能是存储值的容器 。 现在要存储的值取决于程序员是否使用整数,浮点数,字符串

A Variable is like a box in the computer’s memory where you can store a single value. — Al Sweigart

变量就像计算机内存中的一个框,您可以在其中存储单个值。 —阿尔·斯威加特

Unlike in other programming languages, in Python, you need not declare any variables or initialize them. Please read this.

与其他编程语言不同,在Python中,您无需声明任何变量或对其进行初始化。 请阅读

句法 (Syntax)

The general syntax to create a variable in Python is as shown below:

在Python中创建变量的一般语法如下所示:

variable_name = value

variable_name = value

The variable_name in Python can be short as sweet as a, b, x, y, ... or can be very informative such as age, height, name, student_name, covid, ...

variable_name 在Python中可以简短地表示为a, b, x, y, ... ,也可以非常有用,例如age, height, name, student_name, covid, ...

Although it is recommended keeping a very descriptive variable name to improve the readability.

尽管建议保留描述性很强的变量名称以提高可读性。

规则 (Rules)

All set and done, there are some rules that you need to follow while naming a variable:

所有设置和完成,命名变量时需要遵循一些规则:

  • A variable name must start with a letter or the underscore character

    变量名称必须以字母下划线字符开头

  • A variable name cannot start with a number

    变量名不能以数字开头

  • A variable name can only contain alpha-numeric characters and underscores. For example, anything like this is valid: A-z, 0–9, and _

    变量名称只能包含字母数字字符下划线。 例如,类似这样的内容均有效: Az,0–9和_

  • Variable names are case-sensitive (height, Height, and HEIGHT are three different variables names)

    变量名称区分大小写 ( heightHeightHEIGHT是三个不同的变量名称)

(Example)

Below given is an example to properly initialize a value to a variable:

下面给出的示例是将值正确初始化为变量的示例:

# This is a valid and good way to assign a value to a variable
# Let's assign values to variables to calculate the area of a circle
pi = 3.142 # I could have also used "math" library radius = 5 # Interger value for radius
area_of_circle
= 0 # Used to store the value of area of circlearea_of_circle = pi * (radius) ** 2 # Area = (PI * R^2)print("The area of the circle is: ", area_of_circle)

The output of the above code is given below:

上面代码的输出如下:

The area of the circle is:  78.55

绘画示例( 快速浏览 ) (Pictorial Example (Skim it quickly))

I believe just by seeing a picture or an image, the concepts can be understood more quickly. Below is the pictorial representation of a variable and it being stored in the memory.

我相信,仅通过查看图片或图像,就可以更快地理解这些概念。 下面是变量的图形表示,该变量存储在内存中。

Image for post
Photo by Author — Tanu Nanda Prabhu 作者照片— Tanu Nanda Prabhu
Image for post
Photo by Author — Tanu Nanda Prabhu 作者照片— Tanu Nanda Prabhu

全局变量 (Global Variables)

相同的旧定义 (Same old definition)

In Python or any other programming languages, the definition of global variables remains the same, which is “A variable declared outside the function is called global function”. We can access a global variable inside or outside the function.

在Python或任何其他编程语言中,全局变量的定义保持不变,即“ 在函数外部声明的变量称为全局函数 ”。 我们可以在函数内部或外部访问全局变量。

创建一个全局变量并访问它 (Creating a global variable and accessing it)

Let’s use the same example from above to understand the concept of accessing the variable inside and outside the function.

让我们使用上面的相同示例来理解访问函数内部和外部变量的概念。

pi = 3.142       # I could have also used "math" library (math.pi)
radius = 5 # Interger value for radiusdef circle():
area_of_circle = pi * (radius) ** 2
print("The area of the circle is: ", area_of_circle)
circumference_of_circle = 2 * pi * radius# Accessing the global variables outside the functionprint("The circumference of the circle: ", circumference_of_circle)# Accessing the global variables inside the function
circle
()

The output for the above code is given below:

上面代码的输出如下:

The circumference of the circle:  31.419999999999998 
The area of the circle is: 78.55

There you go this is the specialty of global variables. As seen in the above example I have used two common variables pi and radius to calculate the area of the circle which is declared inside a function and area of the circumference which is calculated outside the function. For both these calculations, we are using the same common variables.

到那里,这就是全局变量的特长。 如上例所示,我使用了两个公共变量piradius 计算在函数内部声明的圆的面积和在函数外部计算的圆周的面积。 对于这两种计算,我们使用相同的公共变量。

详细了解“ UnboundLocalError” (Understanding “UnboundLocalError” in detail)

Now let’s take the same old example and try to update the radius by 2 (multiply by 2)

现在,让我们以相同的旧示例为例,尝试更新radius 2乘以2

pi = 3.142       # I could have also used "math" library (math.pi)
radius = 5 # Interger value for radiusdef circle():
radius = radius * 2 # Update the radius by (x 2)
area_of_circle = pi * (radius) ** 2
print("The area of the circle is: ", area_of_circle)circle() # Accessing the global variables inside the function

Now I know you might be like “there is no necessity” of this extra step radius = radius * 2 we can directly do this in the initial step by assigning the value to the radius as 10 i.e. radius = 10. I know but I am trying to introduce a concept here. Please bear with me.

现在,我知道您可能会像这种“多余的步骤”,例如radius = radius * 2一样,“ 我们没有必要 ”,我们可以在初始步骤中通过将半径的值指定为10即radius = 10直接执行此操作。 我知道,但是我想在这里介绍一个概念。 请多多包涵。

As seen in the above code, if you try to update the radius and then execute this piece of code you will be surprised. Don’t be excited and say “I did it” because you didn’t, rather you will be prompted by an error called UnboundLocalError. More likely the error looks like this.

如上面的代码所示,如​​果您尝试更新半径然后执行这段代码,您会感到惊讶。 不要兴奋地说“ 我做了 ”,因为您没有这样做,而是会被称为UnboundLocalError的错误提示 错误更有可能是这样的。

UnboundLocalError: local variable 'radius' referenced before assignment

The reason for this error is that the variable radius is local and it cannot be updated as above. Here, you can make it a global variable. Now how to do it. Please see the below code snippet.

此错误的原因是可变radius 是本地的,因此无法如上所述进行更新。 在这里,您可以将其设为全局变量。 现在该怎么做。 请参见以下代码段。

pi = 3.142       # I could have also used "math" library (math.pi)
radius = 5 # Interger value for radiusdef circle():global radius # Making raduis a global variable
radius = radius * 2 # Update the radius by (x 2)
area_of_circle = pi * (radius) ** 2
print("The area of the circle is: ", area_of_circle)circle()

Now when you execute the code, it executes with no problem. Because now it explicitly declared as a global variable. The output of the above code is given below:

现在,当您执行代码时,它可以毫无问题地执行。 因为现在它显式声明为全局变量。 上面代码的输出如下:

The area of the circle is:  314.2

Time to test your knowledge in the long run. Two years back there was this one question asked in Stack Overflow about UnboundLocalError. The form is now closed for answers because there are already tons of answers present. You can hop in there and try to answer it and understand it more clearly.

从长远来看,该测试您的知识了。 两年前,在Stack Overflow中提出了一个有关UnboundLocalError形式 现在已经关闭了答案,因为已经有大量答案了。 您可以跳到那里,尝试回答并更清楚地理解它。

局部变量 (Local Variables)

相同的旧定义 (Same old definition)

In Python or any other programming languages, the definition of local variables remains the same, which is “A variable declared inside the function is called local function”. We can access a local variable inside but not outside the function.

在Python或任何其他编程语言中,局部变量的定义保持不变,即“ 在函数内部声明的变量称为局部函数 ”。 我们可以在函数内部但不能在函数外部访问局部变量。

创建一个局部变量并访问它 (Creating a local variable and accessing it)

We use the local variables inside a function and not try to access them outside those functions. Hence the name local. But the good part is we can access those variables within the functions itself.

我们在函数内部使用局部变量,而不尝试在那些函数外部访问它们。 因此,名称为local。 但是好的部分是我们可以在函数本身中访问这些变量。

def circle():    pi = 3.142    # I could have also used "math" library (math.pi)
radius = 5 # Interger value for radius
area_of_circle = pi * (radius) ** 2
print("The area of the circle is: ", area_of_circle)
circumference_of_circle = 2 * pi * radius# Accessing the global variables inside the function
circle
()

The output of the above code is:

上面代码的输出是:

The area of the circle is:  78.55

There you go this is the specialty of local variables. As seen in the above example I have used two common variables pi and radius to calculate the area of the circle which is declared inside a function. So accessing these variables will not create any problem. But what happens if we try to access them outside the function. See the next section below.

在那里,这是局部变量的特长。 如上例所示,我使用了两个公共变量piradius 计算在函数内部声明的圆的面积。 因此访问这些变量不会造成任何问题。 但是,如果我们尝试在功能之外访问它们,将会发生什么。 请参阅下面的下一部分。

详细了解“ NameError” (Understanding “NameError” in detail)

Let’s use the same example from above and access the variables declared inside the function:

让我们从上面使用相同的示例,并访问在函数内部声明的变量:

def circle():    pi = 3.142    # I could have also used "math" library (math.pi)
radius = 5 # Interger value for radius
area_of_circle = pi * (radius) ** 2
print("The area of the circle is: ", area_of_circle)
circumference_of_circle = 2 * pi * radius# Accessing the global variables outside the functionprint("The circumference of the circle: ", circumference_of_circle)# Accessing the global variables inside the function
circle
()

When you execute the above code, you will be prompted by a NameError. More likely the error looks like this

当您执行上述代码时,将出现NameError提示 错误更有可能像这样

NameError: name 'pi' is not defined

The reason for this error is as we are trying to access a local variable pi and radius in a global scope whereas the local variable only works inside circle() or local scope. There is a way to solve it by declaring pi and radius as global or declaring them outside the function. Where any function can access them.

发生此错误的原因是因为我们正在尝试访问局部变量pi radius 在全局范围内,而局部变量仅在circle ()或局部范围内起作用。 有一种方法可以通过声明pi来解决 radius 全局或在函数外部声明它们。 任何功能都可以访问它们的地方。

非局部变量 (Nonlocal Variables)

相同的旧定义 (Same old definition)

In Python or any other programming languages, we often use the nonlocal variable inside nested functions. Now, what do I mean by nested functions?

在Python或任何其他编程语言中,我们经常在嵌套函数内使用非局部变量。 现在,嵌套函数是什么意思?

嵌套函数 (Nested Functions)

In general, a nested function is a set of functions declared inside another function. Given below is an example of a nested function.

通常,嵌套函数是在另一个函数内部声明的一组函数。 下面给出的是嵌套函数的示例。

def circle():
pi = 3.142 # I could have also used "math" library (math.pi)
radius = 5 # Interger value for radius
area_of_circle = pi * (radius) ** 2 def circumference(): # Formula for circumference circumference_of_circle = 2 * pi * radius
return circumference_of_circle print(circumference()) # Calling the circumference functionreturn area_of_circleprint(circle()) # Calling the circle function

On executing this piece of code you will get the following as the output

执行这段代码后,您将获得以下输出

31.419999999999998 
78.55

创建一个非局部变量并访问它 (Creating a nonlocal variable and accessing it)

Let us now try to update the radius by 2 (multiply by 2) inside the circumference(). The reason that I’m specifically insisting to do this because as soon as you write radius = radius * 2 and run the code you will be prompted by UnboundLocalError seeing this you will change it to a global variable by saying global radius but this time you will get a new error as NameError. And now you will be baffled, don’t know what to do. There is a simple way to solve this “Go read the definition of a nonlocal variable”. Whenever there is a nested function you need to use a nonlocal variable. That’s it problem solved. Below is the way to create a nonlocal variable and access it.

现在让我们尝试将circumference ()内的半径更新为2(乘以2 circumference () 。 我之所以特别坚持要这样做的原因是,一旦您写入radius = radius * 2并运行代码, UnboundLocalError就会提示您 看到这一点,您可以说出global radius将其更改为全局变量,但这一次您将得到一个新错误,即NameError 。 现在您将感到困惑,不知道该怎么办。 有一个简单的方法可以解决此问题“ 去读取非局部变量的定义 ”。 只要有嵌套函数,就需要使用nonlocal函数 变量。 这样就解决了。 下面是创建非局部变量并对其进行访问的方法。

def circle():    pi = 3.142   # I could have also used "math" library (math.pi)
radius = 5 # Interger value for radius
area_of_circle = pi * (radius) ** 2 def circumference(): nonlocal radius # Nonlocal variable
radius = radius * 2
# Formula for circumference
circumference_of_circle = 2 * pi * radius
return circumference_of_circle print(circumference()) # Calling the circumference functionreturn area_of_circleprint(circle()) # Calling the circle function

On executing this code you will get the output as

执行此代码后,您将获得以下输出:

62.839999999999996 
78.55

结论 (Conclusion)

This is the end of the article titled “Global, Local and Nonlocal variables in Python”. I hope you guys learned a thing or two by reading this article. Through this article, you learned how to get rid of two important Python errors such as NameError and UnboundLocalError which were troubling you all these days or years or whatever. Now you can easily debug these two errors with a smile on your face without losing a sweat. If you have any comments or suggestions about this article, then the comment section is all yours. Stay tuned for more updates, until then goodbye. Stay safe and happy coding and see you next time.

这是标题为“ Python中的全局,局部和非局部变量 ”的文章的结尾。 我希望你们能通过阅读这篇文章学到一两个东西。 通过本文,您学习了如何摆脱两个重要的Python错误,例如NameError UnboundLocalError 这些年来困扰着你的一切 现在,您可以轻松微笑着调试这两个错误,而不会费神。 如果您对本文有任何意见或建议,则注释部分全由您自己承担。 敬请期待更多更新,然后再见。 保持安全快乐的编码状态,下次再见。

翻译自: https://towardsdatascience.com/global-local-and-nonlocal-variables-in-python-6b11c20d73b0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值