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

Amm*_*zal 5 python scope global-variables

所以我对 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 循环内。他们怎么不是本地人?

Pru*_*une 2

您需要比try打开新作用域更强大的东西,例如defclass。您的代码具有与此版本类似的作用域规则:

while True:

    width = int(input("Please enter the width of your floor plan:\n   "))
    height = int(input("Please enter the height of your floor plan:\n   "))
    if width <= 0 or height <= 0:
        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)

我假设您熟悉这个范围。