简体   繁体   中英

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. 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM