def outer():
def inner():
nonlocal ghost
ghost = 1
inner()
outer()
A. 打印 1
B. 抛出 SyntaxError
C. 抛出 NameError
D. 抛出 UnboundLocalError haly 发表于 2026-03-31 06:45
@FishC 执行以下代码后,输出结果是什么?
def out ...
这段代码会引发语法错误(SyntaxError)。
在 Python 中,nonlocal 语句用于在嵌套函数中声明一个变量,该变量来自外层(非全局)作用域。但是,在 outer 函数的作用域中并没有定义 ghost 变量,因此当解释器尝试定义 inner 函数时,会立即抛出 SyntaxError,提示找不到 ghost 的绑定。
所以正确答案是 B. 抛出 SyntaxError。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 @FishC 执行以下代码后,输出结果是什么?
def make_counter():
c = 0
def inc():
nonlocal c
c += 1
return c
return inc
c = make_counter()
print(c(), c(), c())
A. 1 2 3
B. 0 1 2
C. 1 1 1
D. 抛出 UnboundLocalError haly 发表于 2026-03-31 06:49
@FishC 执行以下代码后,输出结果是什么?
def mak ...
代码执行过程如下:
def make_counter():
c = 0
def inc():
nonlocal c
c += 1
return c
return inc
c = make_counter()
print(c(), c(), c())
首先,make_counter() 返回闭包函数 inc,该函数内部引用并修改外层函数的变量 c。初始时 c=0。
第一次调用 c() 时,c 自增为 1 并返回 1。
第二次调用 c() 时,c 从 1 自增为 2 并返回 2。
第三次调用 c() 时,c 从 2 自增为 3 并返回 3。
因此输出为 1 2 3。
答案:A. 1 2 3
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 @FishC 执行以下代码后,输出结果是什么?
def outer():
def inner():
nonlocal ghost
ghost = 1
inner()
outer()
A. 打印 1
B. 抛出 SyntaxError
C. 抛出 NameError
D. 抛出 UnboundLocalError haly 发表于 2026-03-31 06:52
@FishC 执行以下代码后,输出结果是什么?
def out ...
执行这段代码会抛出 SyntaxError,答案是 B。
原因:在 inner 函数中,nonlocal ghost 语句试图声明 ghost 为一个非局部变量,但它在外层函数 outer 的作用域中并不存在。Python 在编译阶段就会检测到这个错误,因此无法正常定义函数,直接抛出语法错误。
其他选项分析:
[*] A:代码中没有打印语句,即使执行也不会输出 1。
[*] C:NameError 通常在运行时引用未定义的变量时抛出,但此处错误发生在编译阶段。
[*] D:UnboundLocalError 是尝试访问未绑定的局部变量时抛出,不符合此场景。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 @FishC 下列代码运行会发生什么?
level = 1
def up():
print(level)
level = level + 1
up()
A. 打印 1
B. 打印 2
C. 抛出 UnboundLocalError
D. 抛出 NameError haly 发表于 2026-03-31 07:24
@FishC 下列代码运行会发生什么?
level = 1
de ...
该代码运行会抛出 UnboundLocalError 错误,因此正确答案是 C。
具体原因如下:
[*]函数 up() 内部使用了变量 level。
[*]由于函数内存在赋值语句 level = level + 1,Python 会将 level 视为函数的 局部变量。
[*]然而,在执行 print(level) 时,这个局部变量 level 还未被赋值,导致程序无法确定它的值,因此抛出 UnboundLocalError(局部变量未绑定错误)。
简单来说:函数试图在给局部变量赋值前,先读取它的值。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
页:
[1]