Technical Roadmap

Function and If-Else Scope

We have learned that Python has 4 main scopes: local, global, enclosing, and built-in.

In this article, we will learn about the difference between scope in a Python function and an if-else statement.

What is Function Scope in Python?

In Python, variables created inside a function have a Local Scope. This means any variable created inside a function cannot be accessed or modified from outside of it.

When we call a function, Python creates a temporary storage area in memory (called a Stack Frame) where all variables inside that function are initialized. When the interpreter reaches the return statement or the end of the code, it releases that memory occupied by that function. The variables are deleted, and the storage is free again.

PYTHON
def hello():
    msg = "Hello from inside!"  # Local variable
    print(msg)

hello()

# This will fail
print(msg)  

Output

Hello from inside!
NameError: name "msg" is not defined

Scope in If-Else in Python

Unlike C++ or Java, Python does not have a block scope for if-else statements. This means any variable you create inside an if block "leaks" out and exists outside of it.

This means a variable you created inside an if in Python can be accessed from outside without declaring it outside. It has a global scope. But this only happens if the if statement is executed, because if the condition in if is false, it will never run and your variables won't be created.

This also creates a logic problem: if the condition is never met and the if never executes, your variable is never created in memory. This will give you a NameError, if you try to use that variable later in your program.

PYTHON
# Condition True
if 10 > 5:
    result = "Success!"

print(result)  # variable leak out

# Condition False
if 10 < 5:
    secret = "I am hidden"

print(secret) # Crash! condition fails 

Output

Success!
NameError: name 'secret' is not defined