python互换变量程序
Here, we are implementing a Python program, that will show the rules about the variable scopes. In the example, we are using the global variable and location variable, accessing, changing their values within their scopes.
在这里,我们正在实现一个Python程序,该程序将显示有关变量作用域的规则。 在示例中,我们使用全局变量和位置变量,在其范围内访问并更改它们的值。
A global variable can be accessed anywhere in the program, it's scope is global to the program, while a local variable can be accessed within the same block in which the variable is declared if we try to access a local variable outside of the scope – it will give an error.
全局变量可以在程序中的任何位置访问,它的范围是程序的全局范围,而如果我们尝试访问范围之外的局部变量,则可以在声明该变量的同一块内访问局部变量。将给出一个错误。
Python代码演示可变范围的示例 (Python code to demonstrate example of variable scopes)
# Python code to demonstrate example
# of variable scopes
# global variable
a = 100
# defining a function to test scopes
def func():
# local variable
b = 200
# printing the value of global variable (a)
# and, local variable (b)
print("a: ", a, "b: ", b)
# main code
if __name__ == '__main__':
# local variable of main
c = 200
# printing values of a, b and c
print("a: ", a) #global
# print("a: ", b) #local of text *** will give an error
print("c: ", c) # local to main
# calling the function
func()
# updating the value of global variable 'a'
a = a+10
# printing 'a' again
print("a: ", a) #global
Output
输出量
a: 100
c: 200
a: 100 b: 200
a: 110
翻译自: https://www.includehelp.com/python/program-to-demonstrate-variables-scope.aspx
python互换变量程序