Python中的try和except块如何使用作用域?

5

我有点困惑于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循环内,我仍然能够打印这些变量。它们为什么不是局部的呢?


3
Python不具有块级作用域。包括trywhile在内的大多数块语句并不会产生新的作用域。(如果它们产生了,我们就需要变量声明来消除变量所属的作用域歧义。) - user2357112
1个回答

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)

我假设您对这个作用域已经很熟悉了。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接