开发者

Python variable scope in if-statements [duplicate]

This question already has answers here: What's the scope of a variable initialized in an if statement? (7 answers) 开发者_运维技巧 Closed 4 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜