【发布时间】:2020-04-16 14:48:31
【问题描述】:
在这段代码 sn-p 中,我忘记在外部范围内定义变量 content。然后我在with 块中为content 赋值。离开with 块后,变量content 的值仍然存在。为什么?
data_dir = "/Users/ugur/code/automating_tools/calibre"
kindle_drm_csv = "amazon_drm_books.csv"
csv_path = f"{data_dir}/{kindle_drm_csv}"
# I forgot to define this:
# content = ""
with open(csv_path, 'r', encoding='utf-8') as csv_file:
# read whole content
content = csv_file.read()
# why could I still print the content of the var?
# shouldn't it be undefined after leaving the `with` block?
print(content)
同样在这个例子中:
if 3<10:
local_var = True
print(local_var)
# prints True
# why?
# I left the if-then-block.
# Shouldn't the local_var be undefined after leaving the block?
【问题讨论】:
-
@Philipp 非常棒。谢谢。但仍然:我的第二个例子无法用你的链接解释。
-
我发送的线程中接受的答案的第一行指出,with、if、for 和 while 不要在 Python 中创建范围。这是否解释了您在第二个示例中的问题?
-
是的。谢谢!
标签: python