所以我对尝试和块的变量范围有些困惑。我的代码如何允许我在尝试块之外的变量,即使我没有在全球范围内分配它们。
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 continuen")
else:
print("Success!")
break
print(width)
print(height)
,即使变量是在try块中定义的,它本身在段循环内,我也能够打印它们。他们不是本地的?
您需要比try
更强大的东西来打开新的范围,例如def
或class
。您的代码具有类似于此版本的范围:
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 continuen")
else:
print("Success!")
break
print(width)
print(height)
我假设您熟悉此范围。