小编Amm*_*zal的帖子

python 中的范围如何与 try 和 except 块一起使用?

所以我对 try 和 except 块的变量范围有点困惑。为什么我的代码允许我使用 try 块之外的变量,甚至 while 循环,即使我没有全局分配它们。

while True:
        try:
            width = int(input("Please enter the width of your floor plan:\n   "))
            height = int(input("Please enter the height of your floor plan:\n   "))
        except:
            print("You have entered and invalid character. Please enter characters only. Press enter to continue\n")
        else:
            print("Success!")
            break
print(width)
print(height)
Run Code Online (Sandbox Code Playgroud)

我再次能够打印变量,即使它们是在 try 块中定义的,而 try 块本身又在 while 循环内。他们怎么不是本地人?

python scope global-variables

5
推荐指数
1
解决办法
5329
查看次数

标签 统计

global-variables ×1

python ×1

scope ×1