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

时间:2017-06-06 00:04:57

标签: 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)

同样,我能够打印变量,即使它们是在try块中定义的,try块本身也在while循环中。他们怎么不在当地?

1 个答案:

答案 0 :(得分:0)

您需要比[First Text, Second Text, Third Text] 强的内容来打开新的范围,例如trydef。您的代码具有与此版本类似的范围规则:

class

我认为你熟悉这个范围。