Python:变量不会被重新赋值 [英] Python: Variables aren't re-assigned

查看:645
本文介绍了Python:变量不会被重新赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么当调用 tst 时,下面的变量(A,B,C,D)不会改变。

  A,B,C = 0,0,0 
D = 0

def tst():
A,B,C = 1,2 ,3
D = 4
print(A,B,C,D)

tst()#tst被称为
print(A,B,C, D)

输出:

(1,2,3,4)
(0,0,0,0)


解决方案

p>在def tst()中,您正在创建局部变量A,B和C,并为它们分配新值。如果您希望将其分配给全局变量,则可以使用

A,B和C值使用全局关键字。


Why aren't the variables below (A,B,C,D) changed when tst is called.

A,B,C = 0,0,0
D = 0

def tst():
    A,B,C = 1,2,3
    D = 4
    print(A,B,C,D)

tst() # tst is called
print(A,B,C,D)

Output:

(1, 2, 3, 4)
(0, 0, 0, 0)

解决方案

because of Python scoping rules.

in def tst(), you're creating local variables A, B, and C, and assigning them new values.

if you wish to assign to the global A,B, and C values, use the global keyword.

这篇关于Python:变量不会被重新赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆