python互换变量程序_Python程序演示变量范围

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互换变量程序

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值