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?

1
  • 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.) Commented Jun 6, 2017 at 0:09

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.