全局变量和局部变量命名规则_变量范围和LEGB规则

全局变量和局部变量命名规则

PYTHON开发人员的提示 (TIPS FOR PYTHON DEVELOPERS)

In the beginning, I assume that you know how to define your own functions — but not only that, you know how to write functions with multiple parameters and can return multiple values using tuples.

首先,我假设您知道如何定义自己的函数-不仅如此,您还知道如何编写具有多个参数的函数并可以使用元组返回多个值。

先决条件 (Prerequisites)

If you do not familiar with defining your own function, the article below will give you more information about it.

如果您不熟悉定义自己的函数,则下面的文章将为您提供有关它的更多信息。

We will now discuss the idea of scope in the context of user-defined functions. You have been defining variables in your programs. So far, you have been using these variables without any problems. However, it would be best if you remembered that not all objects you define are always accessible everywhere in a program. This is the idea of scope, which tells you which part of a program an object or a variable may be accessed.

现在,我们将在用户定义函数的上下文中讨论范围的概念。 您一直在程序中定义变量。 到目前为止,您一直在使用这些变量,没有任何问题。 但是,最好记住,并非定义的所有对象始终在程序中的任何地方都可以访问。 这是范围的概念,它告诉您可以访问程序的哪个部分的对象或变量。

The variables or objects, such as functions that are defined in your program, have a name, as does the function.

变量或对象(例如程序中定义的函数)的名称与函数相同。

There are several types of scope. The first one is the global scope, which means that it is defined in the main body of a script. The second one is the local scope. Local scope means that it is defined within a function. Once the function’s execution is done, any variable inside the local scope terminates, which means you cannot access those variables anymore outside of the function definition.

范围有几种类型。 第一个是全局作用域 ,这意味着它是在脚本主体中定义的。 第二个是本地范围 。 局部作用域意味着它是在函数中定义的。 一旦执行完函数,本地作用域内的任何变量都将终止,这意味着您无法再在函数定义之外访问这些变量。

The third is the built-in scope. This consists of variables in the pre-defined built-ins module, which provides by Python, such as print and sum. The last one is enclosing functions, and we will discuss this later in the nested function section.

第三是内置示波器 。 它由预定义的内置模块中的变量组成,该模块由Python提供,例如print和sum。 最后一个是封闭函数 ,稍后我们将在嵌套函数部分中对此进行讨论。

Let’s check out an example here.

让我们在这里查看示例。

Image for post
Author 作者

We define the function and then call it. If we try to access the variable name value before or

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值