Interview questions

Python Global Variables Interview: The 30-Second Answer and the Traps That Matter

July 30, 2025Updated July 12, 202614 min read
Python Global Variables Interview: The 30-Second Answer and the Traps That Matter

A Python global variables interview guide with a 30-second answer, a compact code example, and the exact difference between reading, shadowing.

You have maybe 30 seconds to answer a question about global variables before the interviewer decides whether you understand Python scoping or just memorised a definition. The answer does not need to be long. It needs to be precise. That is the whole game with python global variables interview questions: the candidate who says the right thing in two sentences sounds more confident than the one who launches into a five-minute tour of the interpreter.

This guide gives you the short answer first, then works through the mechanics that make it true — including the exact error that trips people up, the shadowing trap, and the mutation-versus-rebinding distinction that separates a good answer from a great one.

Lead with the 30-second answer, not the textbook

What the memorisable answer should sound like

Here is the script. Say it out loud until it feels natural:

"In Python, a variable defined at module level is global. Any function can read it through normal name lookup. But if you assign to that name inside a function, Python treats it as a local variable for the entire function body — which means an earlier read of the same name will raise an UnboundLocalError if the assignment comes after. If you genuinely need to rebind the module-level name from inside a function, you declare `global x` at the top of the function."

That is it. Precise, covers the three distinct behaviors, and takes under 30 seconds. The goal is not to sound encyclopedic — it is to sound like someone who has actually been bitten by this and knows why.

What this looks like in practice

The critical thing to point out in an interview is the second function: `x = 99` does not update the global. It creates a brand-new local name that shadows the global inside that scope. The module-level `x` is untouched. That one sentence — "assignment inside a function creates a local, it does not update the global" — is what interviewers are listening for.

Python global variables work because scope is decided before the function runs

Why reading a global works but assigning does not

Python uses the LEGB rule to resolve names: Local, Enclosing, Global, Built-in. When a function reads a name it has not assigned, Python walks up that chain and finds it at the Global level. That is why reading a global just works with no extra syntax.

The structural mismatch kicks in the moment there is an assignment. Python does not resolve scopes at runtime — it does so at compile time, when it scans the function body. If it sees an assignment to a name anywhere in the function, it marks that name as local for the entire function. This is a static decision made before the function runs. LEGB still applies for reads, but a name flagged as local will never be looked up at the Global level, regardless of where in the function body the assignment appears.

This is the point where interviewers separate candidates who understand the model from candidates who have only seen the happy path. Knowing LEGB is table stakes. Knowing that the local-or-global decision is made before execution is the answer that earns a follow-up.

What this looks like in practice

Remove the `x = 99` line and the first `print(x)` works perfectly — it finds `x` at the Global level. Add the assignment back and the compile-time decision changes: `x` is now local throughout, so the first `print` is trying to read a local that does not yet have a value. The function never even reaches the assignment before the error fires.

Python global variables interview answers fail when people skip UnboundLocalError

Why Python raises UnboundLocalError

The error is not random and it is not a runtime surprise — it is the direct consequence of the compile-time scope decision described above. Python has already decided that `x` is a local variable. When execution reaches the `print(x)` line before the assignment, it looks for a local named `x`, finds nothing, and raises `UnboundLocalError: local variable 'x' referenced before assignment`.

This is the exact message. Not `NameError`. Not `ScopeError`. `UnboundLocalError` — which tells you specifically that the name exists as a local binding, it just has not been assigned a value yet. That distinction matters in an interview because it shows you understand the error class, not just that "something went wrong."

What this looks like in practice

The fix is either to declare `global counter` at the top of the function, or — better — to redesign the function so it does not rely on rebinding a global. Remove the `counter = counter + 1` line entirely and the `print` works. That is the diagnostic: the error exists only because the assignment is there, because the assignment is what made `counter` local in the first place.

An interviewer who hears a candidate say "Python decides the scope at compile time, so the assignment later in the function is what causes the earlier read to fail" is going to trust that candidate with a codebase.

Shadowing is the trap that makes good candidates sound confused

The name is the same, but the variable is not

Shadowing is not a bug — it is a naming collision that Python resolves in a predictable way. When a local name and a global name are identical, the local name wins inside the function. The global still exists at module level, completely untouched. The local just hides it within that function's scope.

The confusion happens when a candidate tries to both read and assign the same name inside one function without declaring `global`. They expect the read to see the global and the write to update it. What actually happens is Python marks the name local for the whole function, the read fails with `UnboundLocalError`, and the candidate is left wondering why a name that clearly exists is raising an error.

Shadowing is harmless when you only assign. It becomes a trap the moment you try to read before you assign.

What this looks like in practice

Inside `show_shadow`, `count` refers to the local. Outside, `count` is still 100. The same identifier points to two completely separate objects depending on scope. This is the clean version — the local is assigned before it is read, so there is no error. The trap version is when someone tries `print(count)` before `count = 5` inside the same function and hits `UnboundLocalError` because the compile-time decision has already flagged `count` as local.

global fixes rebinding, not every kind of change

When the global keyword is actually doing work

The `global` keyword in Python tells the compiler: treat this name as the module-level binding, not a local one. It is about rebinding — pointing the name at a new object — not about granting special access to an object that already exists. If you want to update a module-level integer or string, you need `global` because integers are immutable and the only way to "update" them is to rebind the name to a new value.

What `global` does not do is change how Python handles objects you are mutating rather than replacing. If the module-level name points to a list or a dict, you can call `.append()` or update a key from inside a function without `global`, because you are not rebinding the name — you are modifying the object the name already points to.

What this looks like in practice

`total` requires `global` because `total = total + value` is a rebinding operation — it creates a new integer and points `total` at it. `items.append(value)` does not rebind anything; it calls a method on the object that `items` already references. Remove `global total` and you get `UnboundLocalError`. Remove nothing from the `items` line and it works fine either way.

This is the mental model most guides blur: mutation and rebinding are not the same operation, and `global` is only required for the latter.

global vs nonlocal is where nested functions reveal who really understands scope

The difference interviewers are actually testing

`global` and `nonlocal` both exist to reach outside a function's local scope, but they target different levels of the LEGB chain. `global` always reaches the module-level scope — the G in LEGB. `nonlocal` reaches the nearest enclosing function scope — the E in LEGB — which is only meaningful inside a nested function.

They solve different problems. If you are inside a nested function and you want to rebind a variable from the outer function, `nonlocal` is correct. If you use `global` instead, you will either create a new module-level variable or modify one that already exists there — either way, the outer function's variable is untouched. That is the exact distinction interviewers probe when they ask about global vs nonlocal Python behavior.

What this looks like in practice

Swap `nonlocal` for `global` and the behavior changes completely: `x = 99` creates or updates a module-level variable named `x`, and `outer()`'s local `x` stays at 10. The nesting level being targeted is the whole point. `nonlocal` is for the enclosing function; `global` is for the module. They are not interchangeable, and the fact that they look similar is exactly why interviewers use this question to separate candidates who have thought about scoping from those who have only used it.

When to avoid globals so your answer sounds like someone who ships code

The safe alternative is often simpler

Globals are not forbidden. Module-level constants — `MAX_RETRIES = 3`, `DEFAULT_TIMEOUT = 30` — are idiomatic Python and completely fine. The problem is mutable global state that gets modified from multiple functions. That pattern makes code hard to reason about because any function anywhere in the module can change the state, and tracing a bug means auditing every function that touches the global.

The failure mode most guides skip is not that globals raise errors — it is that they make the program's behavior depend on call order in ways that are invisible at the call site. A function that takes arguments and returns values is self-contained; its behavior is visible from its signature. A function that reads and writes a global is not.

What this looks like in practice

The refactor is usually straightforward. Instead of:

Return the value and let the caller manage state:

Or wrap shared state in a class:

Interviewers like the second or third answer because it demonstrates that the candidate knows when to use a feature and when to design around it. Saying "I'd prefer to return the value or encapsulate the state in an object so the mutation is explicit" is the kind of answer that moves a candidate from the "knows Python" column to the "writes maintainable Python" column.

FAQ

What is the best 30-second answer for explaining Python global variables in an interview?

Variables defined at module level are global; functions can read them through normal LEGB lookup, but any assignment to the same name inside a function makes Python treat that name as local for the entire function body. To rebind a module-level name from inside a function, declare `global name` at the top of the function. That three-part answer — read is fine, assignment changes the scope classification, `global` fixes rebinding — covers every follow-up an interviewer is likely to ask.

Why does Python raise UnboundLocalError when you assign to a global name inside a function?

Python decides at compile time whether a name is local or global, based on whether the function body contains an assignment to that name. If an assignment exists anywhere in the function, the name is classified as local for the whole function — including lines before the assignment. When execution reaches a read of that local before it has been assigned a value, Python raises `UnboundLocalError: local variable 'x' referenced before assignment`. The error is not a runtime surprise; it is the direct consequence of the compile-time decision.

What is the difference between reading a global variable and modifying it inside a function?

Reading is a lookup that walks the LEGB chain — no special syntax required. Modifying is more nuanced: if you are mutating an object (appending to a list, updating a dict key), no `global` declaration is needed because you are operating on the object, not rebinding the name. If you are rebinding the name — assigning a new integer, string, or any new object — you need `global` because otherwise Python classifies the name as local and the assignment never touches the module-level binding.

How does shadowing work when a local variable has the same name as a global variable?

Inside the function, the local name wins — the global is hidden but not changed. If you assign `count = 5` inside a function where `count = 100` exists at module level, the function's `count` is a completely separate object. Outside the function, `count` is still 100. Shadowing becomes a trap when the same function tries to read the name before assigning it, because Python has already marked it local — the read hits `UnboundLocalError` even though the global clearly exists.

What is the difference between global and nonlocal in Python?

`global` targets the module scope; `nonlocal` targets the nearest enclosing function scope. `nonlocal` only makes sense inside a nested function where there is an outer function whose variable you want to rebind. Using `global` in that situation does not reach the outer function — it reaches the module level, leaving the outer function's variable untouched. The distinction maps directly to the G and E levels of LEGB.

When do you need global, and when can you avoid it by mutating an object or returning a value instead?

Use `global` when you genuinely need to rebind a module-level name from inside a function — configuration resets, module-level counters in small scripts. Avoid it when you can return the updated value instead, or when the shared state belongs inside a class. Mutating a list or dict in place does not require `global` at all. The cleaner design almost always makes the state change explicit at the call site, which makes the code easier to test and debug. Saying this in an interview signals that you think about maintainability, not just correctness.

How Verve AI Can Help You Ace Your Software Engineer Coding Interview

Technical rounds for software engineering roles move fast — a Python scoping question lands, you have seconds to structure a coherent answer, and the follow-up comes before you have finished the first sentence. That is exactly the scenario the Verve AI Coding Copilot is built for. During a live coding interview on Zoom, Google Meet, or Teams, it reads your screen in real time — seeing the problem as it appears — and surfaces structured suggestions as you work through it, so you are never staring at a blank editor trying to remember whether mutation requires `global`. The desktop app stays invisible during screen share, which means the support is there without changing how the interview looks from the other side. It works across LeetCode, HackerRank, CodeSignal, and live technical rounds. Before the real interview, the separate Mock Interviews feature lets you rehearse the scoping questions, the edge cases, and the verbal explanation so the 30-second answer feels natural when it counts.

---

You now have the short answer, the code that proves it, and the exact error message that separates a vague explanation from a credible one. Before your interview, say the 30-second script out loud at least twice — not to memorise it word for word, but to feel where it flows and where you stumble. Keep the `UnboundLocalError` snippet somewhere accessible. The question is not hard. The follow-up is. And you are ready for it.

JM

James Miller

Career Coach

Related reads

Explore Related Interview Guides

What Essential Questions For Mcdonalds Interview Should You Master
July 17, 2025Interview prep guide

What Essential Questions For Mcdonalds Interview Should You Master

Get insights on questions for mcdonalds interview with proven strategies and expert tips.

Read guide
What Essential Role Does A Mini Bouquet Play In Landing Your Dream Job Or Client
September 11, 2025Interview prep guide

What Essential Role Does A Mini Bouquet Play In Landing Your Dream Job Or Client

Get insights on mini bouquet with proven strategies and expert tips.

Read guide
What Essential Role Does Your Cover Letter For Teaching Position Play In Securing The Dream Job
August 14, 2025Interview prep guide

What Essential Role Does Your Cover Letter For Teaching Position Play In Securing The Dream Job

Get insights on cover letter for teaching position with proven strategies and expert tips.

Read guide
What Essential Role Does Your Interview Attire Play In Securing Your Next Opportunity?
August 31, 2025Interview prep guide

What Essential Role Does Your Interview Attire Play In Securing Your Next Opportunity?

Get insights on interview attire with proven strategies and expert tips.

Read guide
What Essential Secrets Does The Account Manager Job Description Hold For Interview Success?
August 31, 2025Interview prep guide

What Essential Secrets Does The Account Manager Job Description Hold For Interview Success?

Get insights on account manager job description with proven strategies and expert tips.

Read guide
What Essential Skills And Strategies Will Help You Secure A Target Warehousr Job Moreno Balley?
September 4, 2025Interview prep guide

What Essential Skills And Strategies Will Help You Secure A Target Warehousr Job Moreno Balley?

Get insights on target warehousr job moreno balley with proven strategies and expert tips.

Read guide
What Essential Skills Define A Successful Client Relationship Partner
August 29, 2025Interview prep guide

What Essential Skills Define A Successful Client Relationship Partner

Get insights on client relationship partner with proven strategies and expert tips.

Read guide
What Essential Skills Define A Successful Fashion Representative
September 4, 2025Interview prep guide

What Essential Skills Define A Successful Fashion Representative

Get insights on fashion representative with proven strategies and expert tips.

Read guide
What Essential Skills Do Human Resource Specialists Need To Master For Interview Success
September 2, 2025Interview prep guide

What Essential Skills Do Human Resource Specialists Need To Master For Interview Success

Get insights on human resource specialist with proven strategies and expert tips.

Read guide

Ace your live interviews with AI support!

Get Started For Free

Available on Mac, Windows and iPhone