我有点困惑于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循环内,我仍然能够打印这些变量。它们为什么不是局部的呢?
try
和while
在内的大多数块语句并不会产生新的作用域。(如果它们产生了,我们就需要变量声明来消除变量所属的作用域歧义。) - user2357112