5

So I am a bit confused about the scoping of variables with try and except blocks. How come my code allows me to use the variables outside of the try block and even the while loop for that matter even though I have not assigned them globally.

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)

Again I am able to print the variables even if they are defined within a try block which itself is within a while loop. How are they not local?

Ammar Khazal
  • 133
  • 3
  • 9
  • 3
    Python isn't block scoped. Most block statements, including `try` and `while`, do not generate a new scope. (If they did, we'd need variable declarations to disambiguate the intended scope of a variable.) – user2357112 Jun 06 '17 at 00:09

1 Answers1

2

You need something stronger than try to open a new scope, such as def or class. Your code has scoping rules similar to this version:

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)

I assume that you're familiar with this scoping.

Prune
  • 76,765
  • 14
  • 60
  • 81