Python variables are scoped to the innermost function, class, or module in which they're assigned. Control blocks like if and while blocks don't count, so a variable assigned inside an if is still scoped to a function, class, or module.

(Implicit functions defined by a generator expression or list/set/dict comprehension do count, as do lambda expressions. You can't stuff an assignment statement into any of those, but lambda parameters and for clause targets are implicit assignment.)

Answer from Luke Maurer on Stack Overflow
Discussions

How Does Scope in Python Work?
Only functions and classes introduce new scopes in Python. Control flow blocks share their "outer" scope. More on reddit.com
🌐 r/learnpython
11
2
January 18, 2021
Can I use a variable initialized in an `if` statement outside of it?
I know that the variable scope and context within with and range statements only apply within them. A variable can be created within them but can only then be used within them, not outside. If you want to use it outside, you have to create the variable outside the statement first and then only ... More on discourse.gohugo.io
🌐 discourse.gohugo.io
2
0
August 5, 2022
Python life variables in if statement - Stack Overflow
Control blocks like if and while blocks don't count, so a variable assigned inside an if is still scoped to a function, class, or module. However Implicit functions defined by a generator expression or list/set/dict comprehension do count, as do lambda expressions. You can't stuff an assignment statement into any of those, but lambda parameters and for clause targets are implicit assignment. ... Note that a isn't declared or initialized before the condition unlike C or Java, In other words, Python ... More on stackoverflow.com
🌐 stackoverflow.com
Python: How can I use a variable outside of an if statement
I’m trying to create a path creation script. I check if the object does not have a path and create the path variable. I then change a property so that the object knows that it now has a path. if own["hasPath"] == 0: … More on blenderartists.org
🌐 blenderartists.org
4
0
June 9, 2010
People also ask

How can I avoid `NameError` exceptions due to variable scope?
A: Always ensure that a variable is initialized before use. Using structured control flow with explicit initialization can mitigate this risk.
🌐
sqlpey.com
sqlpey.com › python › solved-how-to-understand-variable-scope-in-python-if-statements
Solved: How to Understand Variable Scope in Python's If Statements
Are there any potential pitfalls with Python's scoping rules?
A: Yes, particularly in larger codebases or when reusing variables, which can lead to unexpected behavior due to variable shadowing or unintended access to global variables.
🌐
sqlpey.com
sqlpey.com › python › solved-how-to-understand-variable-scope-in-python-if-statements
Solved: How to Understand Variable Scope in Python's If Statements
Why doesn't Python adhere to block-level scoping like C or Java?
A: Python is designed to simplify variable management, leading to a more flexible scoping approach where variables exist across the entire function or module rather than being restricted to specific blocks.
🌐
sqlpey.com
sqlpey.com › python › solved-how-to-understand-variable-scope-in-python-if-statements
Solved: How to Understand Variable Scope in Python's If Statements
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-scope-of-variables
Python Scope of Variables - GeeksforGeeks
July 12, 2025 - Any variable which is changed or created inside of a function is local, if it hasn’t been declared as a global variable. To tell Python, that we want to use the global variable, we have to use the keyword global, as can be seen in the following ...
🌐
Quora
quora.com › If-a-variable-is-declared-within-an-if-then-else-does-it-still-exist-when-the-if-then-else-is-finished-Why-or-why-not
If a variable is declared within an if-then-else, does it still exist when the if- then-else is finished? Why or why not? - Quora
Answer (1 of 5): It will be different within different languages. In C the answer is NO since c is a block scoped language, and an if block is a separate scope item. In C. It is if/else, not if/then/else. In Python the answer is yes since Python is function/module scoped and an if block is NOT ...
🌐
Reddit
reddit.com › r/learnpython › how does scope in python work?
r/learnpython on Reddit: How Does Scope in Python Work?
January 18, 2021 -

Trying to understand how scope works in Python. It seems to work a bit differently than in other languages like C++ and Java. When I run the code below

def foo():
    y = 5

x = 2
foo()
print(x+y)

it returns a name not defined error. That's expected since the scope of y disappeared before it could be used. However, when I run the following code

x = 2
if True:
    y = 3
print(x+y)

It works just fine. The program identifies y even though it is in another scope. When trying out the same thing in other languages like C++

int x = 2;
if (true)
{
    y = 2;
}
cout<<x + y<<endl;

it gives a not declared in this scope error. That's what I expected in Python but clearly that's not the case. Python somehow keeps track of variables inside the scope of an if statement or loop even after it exits and the variables were not declared outside of it. Can anyone explain how scope in Python differs from scope in C++ or Java? How does Python treat scope differently?

🌐
W3Schools
w3schools.com › python › python_scope.asp
Python Scope
A variable created outside of a ... one available in the global scope (outside the function) and one available in the local scope (inside the function):...
Find elsewhere
🌐
HUGO
discourse.gohugo.io › support
Can I use a variable initialized in an `if` statement outside of it? - support - HUGO
August 5, 2022 - A variable can be created within them but can only then be used within them, not outside. If you want to use it outside, you have to create the variable outside the statement first and then only reassign the value.
🌐
sqlpey
sqlpey.com › python › solved-how-to-understand-variable-scope-in-python-if-statements
Solved: How to Understand Variable Scope in Python's If Statements
December 5, 2024 - Python utilizes a specific order to search for variables: ... Notably, constructs like if, for, and other loop structures do not create a new scope. Thus, any variable defined in these contexts shares the same scope as any defined outside them.
🌐
Appdividend
appdividend.com › define-a-variable-inside-if-statement-in-python
How to Define a Variable inside If Statement in Python
April 30, 2025 - Variables in if blocks follow the same scope as their enclosing function/module. For example, if you are initializing a variable inside the if block and printing its value outside of the scope of the if statement.
🌐
DataCamp
datacamp.com › tutorial › scope-of-variables-python
Python Variable Scope And The LEGB Rule Explained | DataCamp
September 11, 2025 - Keywords (such as if, for, def) are part of Python’s syntax, not the built-in namespace, and can never be used as identifiers. Python’s block statements and comprehensions have specific scoping behaviors that often surprise developers coming from other languages. Assignments inside these blocks affect the containing scope (function or module). Loop variables also remain defined after the loop ends.
🌐
Open Textbook
open.oregonstate.education › computationalbiology › chapter › variables-and-scope
Variables and Scope – A Primer for Computational Biology
June 21, 2019 - In Python, on the other hand, variables declared in if-statements, for-loop blocks, and while-loop blocks are not local variables, and stay in scope outside of the block. Thus we say that C++ has “block-level” scoping, while Python uses ...
🌐
Blender Artists
blenderartists.org › game engine › game engine support and discussion
Python: How can I use a variable outside of an if statement - Game Engine Support and Discussion - Blender Artists Community
June 9, 2010 - I’m trying to create a path creation script. I check if the object does not have a path and create the path variable. I then change a property so that the object knows that it now has a path. if own["hasPath"] == 0: path = fillList() own["hasPath"] = 1 Whenever I try to use the variable outside of the if statement I get an error that it is not defined.
🌐
Alma Better
almabetter.com › bytes › tutorials › python › python-variable-scope
Variable Scope in Python
February 16, 2024 - In Python, the scope of a variable is decided by where it is declared. A variable declared within an if statement is only accessible inside the statement.
🌐
DEV Community
dev.to › stoicperlman › comment › 28e9
Python variable scope inside an if statement. if True: var = “something... - DEV Community
February 6, 2018 - But var doesn't exist on line 3!! I know different rules for different languages, but allowing this would drive me crazy (esp. if you are just saving an explicit var = null statement) ... B.Sc. Computer Science and Mathematics ... with open('foo.txt', 'w') as f: f.write('hello world\n') f.write('also hello world\n') # f is closed by still in scope!
🌐
Studytonight
studytonight.com › python-howtos › scope-of-the-variable-initialised-in-the-if-statement
Scope of the variable initialised in the if statement - Studytonight
February 9, 2021 - So, anything declared in an if block has the same scope as anything declared outside the block. Variables are not checked at compile-time, which is why other languages throw an exception.
🌐
Python Academy
python-academy.org › course › scope of variables
Scope of variables — Interactive Python Course
global scope: anything declared in the main body of the program, visible inside every function · local scope: variables declared inside a function, alive only while that function is running
🌐
Quora
quora.com › How-can-I-add-to-a-variable-in-an-if-statement-in-python
How to add to a variable in an 'if statement' in python - Quora
Answer (1 of 4): As the others have attempted to show, your problem lies in the “type” of the data contained in that variable. Even though Python uses dynamic types, it uses strong types. I.e. it adjusts the type to what is input/created, but it doesn’t simply convert willy-nilly between ...
🌐
Evanjones
evanjones.ca › python-pitfall-scope.html
Python Pitfalls: Scope (evanjones.ca)
On occasion I'll define a variable inside a loop or if statement, and then mistakenly use it afterwards. This will work until the program flow changes, for whatever reason, and then suddenly the variable is no longe defined. Here is a slightly modified example of this program to illustrate what I am talking about: one = 1 if one == 1: two = 2 print one print two else: print one print one print two