Python variable scope in if-statements

Question:

In Python, are variable scopes inside if-statements visible outside of the if-statement? (coming from a Java background, so find this a bit odd)

In the following case, name is first defined inside the if-block but the variable is visible outside of the if-block as well. I was expecting an error to occur but ‘joe’ gets printed.

if 1==1:
    name = 'joe'
print(name)
Asked By: Glide

||

Answers:

if statements don’t define a scope in Python.

Neither do loops, with statements, try / except, etc.

Only modules, functions and classes define scopes.

See Python Scopes and Namespaces in the Python Tutorial.

Answered By: agf

Yes, in Python, variable scopes inside if-statements are visible outside of the if-statement.
Two related questions gave an interestion discussion:

Short Description of the Scoping Rules?

and

Python variable scope error

Answered By: Remi

All python variables used in a function live in the function level scope. (ignoring global and closure variables)

It is useful in case like this:

if foo.contains('bar'):
   value = 2 + foo.count('b')
else:
   value = 0

That way I don’t have to declare the variable before the if statement.

Answered By: Winston Ewert
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.