[英]Why can't you change a variable in a global/nonlocal/return statement in python 3?
In javascript I'm used to being able to var a=5
or return a=5
but in python if I try global a=5
, nonlocal a=5
or return a=5
I get an error. 在javascript中,我习惯于能够
var a=5
或return a=5
但是在python中,如果我尝试使用global a=5
, nonlocal a=5
或return a=5
则会收到错误消息。 Is there a reason behind why you can't or am I just doing something wrong 为什么您做不到或我只是做错了什么原因?
In some languages it is common practice to stick an assignment inside of another statement. 在某些语言中,通常将分配赋值放在另一个语句中。 For example,
例如,
if a = 1 { ... }
the Python developers decided this is a source of bugs since it is too close to Python开发人员认为这是bug的来源,因为它太接近了
if a == 1:
Therefore, they banned the nesting of assignments inside of other statements. 因此,他们禁止在其他语句内部嵌套分配。 Since
以来
global a
is a statement unto itself, an assignment inside of the statement is not allowed. 是一个本身的语句,不允许在语句内部进行赋值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.