Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python variable scope in if-statements [duplicate]

Tags:

python

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) 
like image 236
Glide Avatar asked Sep 12 '11 01:09

Glide


People also ask

DO IF statements change scope?

Does an if statement create a new scope? The body of an if statement does not create a new scope. Any variables assigned within the body of an if statement will modify the scope that the if statement itself is in.

DO IF statements have scope in Python?

Scope of a Variable in If Statement Unlike languages such as C, a Python variable is in scope for the whole of the function (or class, or module) where it appears, not just in the innermost "block". So, anything declared in an if block has the same scope as anything declared outside the block.

Can you declare variables in an if statement Python?

If you're new to the syntax that's used in the code sample, if (int i = 5) { is a perfectly valid way of declaring and defining a variable, then using it inside the given if statement.

Can you declare a variable in an if statement?

Variable scope. Java allows you to declare variables within the body of a while or if statement, but it's important to remember the following: A variable is available only from its declaration down to the end of the braces in which it is declared.


1 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.

like image 109
agf Avatar answered Sep 23 '22 06:09

agf