赛派号

十大名牌豆浆机排行榜 Variable Scope in Python

Variable Scope in Python

In general, a variable that is defined in a block is ailable in that block only. It is not accessible outside the block. Such a variable is called a local variable. Formal argument identifiers also behe as local variables.

The following example will underline this point. An attempt to print a local variable outside its scope will raise the NameError exception.

Example: Local Variabledef greet(): name = 'Steve' print('Hello ', name) greet() print(name) #NameErrorTry it

Here, name is a local variable for the greet() function and is not accessible outside of it.

Any variable present outside any function block is called a global variable. Its value is accessible from inside any function. In the following example, the name variable is initialized before the function definition. Hence, it is a global variable.

Example: Global Variablename='John' def greet(): print ("Hello ", name) greet() print(name)Try it

Here, you can access the global variable name because it has been defined out of a function.

However, if we assign another value to a globally declared variable inside the function, a new local variable is created in the function's namespace. This assignment will not alter the value of the global variable. For example:

Example: Local and Global Variablesname = 'Steve' def greet(): name = 'Bill' print('Hello ', name) #Hello Bill greet() print(name) #steveTry it

Now, changing the value of global variable name inside a function will not affect its global value.

If you need to access and change the value of the global variable from within a function, this permission is granted by the global keyword.

Example: Access Global Variablesname = 'Steve' def greet(): global name name = 'Bill' print('Hello ', name) greet() print(name) #BillTry it

The above would display the following output in the Python shell.

It is also possible to use a global and local variable with the same name simultaneously. Built-in function globals() returns a dictionary object of all global variables and their respective values. Using the name of the variable as a key, its value can be accessed and modified.

Example: Global Variablesname = 'Steve' def greet(): globals()['name'] = 'Ram' name='Steve' print ('Hello ', name) greet() print(name) #RamTry it

The result of the above code shows a conflict between the global and local variables with the same name and how it is resolved.

Visit Globals and Locals in Python for more information.

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至lsinopec@gmail.com举报,一经查实,本站将立刻删除。

上一篇 没有了

下一篇没有了