Python variable scope in if-statements [duplicate]
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)
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.
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
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.
精彩评论