简体   繁体   English

为变量分配新值时出错

[英]error while assigning a new value to a variable

I was working with scope in python我在 python 中使用范围

a = 10
{
    a = 33
}

and I got this error,我得到了这个错误,

File "", line 3 a= 33 ^ SyntaxError: invalid syntax文件“”,第 3 行 a=33 ^ SyntaxError:无效语法

so it means block scope is only for functions in python?所以这意味着块范围仅适用于python中的函数吗?

def foo():
    a = 33
    print(f"Inside: {a}") # Inside: 33

a = 10
foo()
print(f"Outside: {a}") # Outside: 10

I think this example of function scope is the only way to get something like block scope in Python.我认为这个函数作用域的例子是在 Python 中获得类似块作用域的唯一方法。 Idea taken from OP and confirmed in Block scope in Python取自 OP 并在 Python 的 Block 范围内确认的想法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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