Interview questions

Python Global Variables Interview: The 30-Second Answer and the Edge Cases

July 30, 2025Updated May 20, 202615 min read
Can Python Globale Variable Be The Secret Weapon For Acing Your Next Interview

A practical Python global variables interview guide with the 30-second answer, local vs global scope rules, shadowing, UnboundLocalError, global vs nonlocal.

Here is the 30-second answer you can say out loud right now. Then we'll make sure you can survive the follow-up — because in a python global variables interview, the follow-up is where most candidates lose the point.

A global variable is defined at module level, outside any function. A local variable is created inside a function and only exists for the duration of that call. Python lets you read a global from inside a function without any special syntax. The trap is assignment: the moment you assign to a name inside a function, Python marks that name as local — not because of what you intended, but because of what the interpreter sees at compile time. If you then try to read that name before assigning it, you get an `UnboundLocalError`. The fix is a `global` declaration at the top of the function, which tells Python you mean the module-level name, not a new local one.

That's the whole answer. The rest of this guide unpacks why each piece of that works, shows you the code examples that prove it, and covers the edge cases — mutable globals, `nonlocal`, and when the right answer is to stop using globals entirely.

Say the 30-second answer first, then prove you know the rules

The answer interviewers actually want to hear

Here is the answer verbatim, the way it sounds in a mock session or a live technical screen:

"A global variable in Python is one that's defined at module scope — outside any function or class. A local variable is created inside a function and only exists for that function's lifetime. You can read a global from inside a function without declaring anything. But if you assign to a name inside a function, Python treats that name as local from that point forward — even if a global with the same name exists. To rebind a global from inside a function, you have to explicitly declare it with the `global` keyword."

That answer covers three things: definition, access, and the assignment rule. It signals that you understand Python's scope model, not just the vocabulary. Interviewers who ask this question in a python global variables interview are almost always testing whether you know the assignment-changes-scope rule, because that's where the bugs actually come from.

What this looks like in practice

This is the clean case. `show_count` reads `count` without touching it, so Python finds it in module scope through the LEGB lookup chain (Local → Enclosing → Global → Built-in), as described in Python's official documentation on scope and name resolution. You can explain every line of this in an interview without hesitation, and that confidence matters as much as correctness.

Local vs global variables in Python is simpler than people make it sound

Why the simple definition is enough if you say it cleanly

The textbook definition — global means module-level, local means inside a function — is actually correct. The problem is that candidates say it too quickly and then get stuck the moment the interviewer asks "but what if the function tries to change it?" Understanding Python global vs local variables isn't about memorizing a longer rule; it's about knowing the one wrinkle that makes the simple rule feel complicated.

In roughly two-thirds of the mock interview sessions I've reviewed, candidates confuse "where a variable is defined" with "where it can be accessed." A global variable defined at module level can be read from anywhere in the module, including inside functions. That's not a violation of anything — it's how the LEGB lookup works. The confusion starts when people assume that "accessible" means "writable without declaration," and it doesn't.

What this looks like in practice

`shadow_it` doesn't modify the global. It creates a completely separate local variable that happens to share the same name. After `shadow_it` returns, that local is gone. The global `message` is unchanged. This is called shadowing, and it's not an error — it's intentional behavior in Python's scope model. The key insight for the interview: defining a local with the same name as a global doesn't destroy the global; it just hides it for the duration of that function call.

Assignment inside a function changes the rules, and that's the whole trick

Why Python decides a name is local the moment you assign to it

The global keyword in Python exists because of a design decision Python makes before your function ever runs. When the interpreter compiles a function, it scans the function body for any assignment statements. If it finds `x = something`, it marks `x` as a local variable for that entire function — not just after the assignment line, but for the whole function. This is static scope analysis, not runtime guessing.

This is the key distinction that separates a good answer from a great one: Python isn't confused about what you intended. It made a deliberate, consistent decision at compile time. If you want it to treat `x` as a global, you have to say so explicitly with `global x` before any assignment.

What this looks like in practice

Without `global total`, the line `total = total + 10` would fail. Python would see the assignment on the left side, classify `total` as local, then try to read `total` on the right side before any local value exists. With `global total`, Python knows to look in module scope for both the read and the write.

When that same code becomes a trap

This looks reasonable to a human. The function reads `total`, adds 10, and assigns it back. But Python has already decided `total` is local because of the assignment on the left. When execution reaches the right side of the assignment, there is no local `total` yet. The error fires before the addition happens. This is the trap, and it's the most common Python scope bug in entry-level code.

UnboundLocalError is Python telling you your mental model is wrong

Why this error shows up even when a global exists

`UnboundLocalError` in Python doesn't mean the name doesn't exist anywhere. It means the name exists as a local variable in this function's namespace, and you tried to read it before giving it a value. The global with the same name is irrelevant — Python already decided it's not looking there. The error is Python being honest about the mismatch between what you wrote and what the scope rules require.

This is also why `UnboundLocalError` is different from `NameError`. A `NameError` fires when a name doesn't exist in any scope. An `UnboundLocalError` fires when a name exists as a local but hasn't been assigned yet. The distinction matters in an interview because it shows you understand the two-step process: scope classification happens at compile time, value assignment happens at runtime.

What this looks like in practice

Here's the debug trace that makes this concrete. When `increment` is called, Python's local namespace for that call is `{}` — empty. Line A tries to read `counter` from local scope first. Python finds it in the local namespace classification (because line B assigned to it), but the local value hasn't been set yet. The error fires at line A, not line B. That ordering surprises most candidates the first time they see it. The Python language reference documents this behavior directly under the global statement specification.

global and nonlocal are not the same escape hatch

Use global when you mean module scope, not whenever a function needs to change something

The distinction between nonlocal vs global Python is one interviewers use specifically to check whether you've actually written nested functions or just read about them. `global` reaches all the way to module scope — the top level of the file. `nonlocal` reaches to the nearest enclosing function scope that isn't the global scope. They solve different problems, and using one when you need the other produces a runtime error or silent misbehavior.

In code review experience, `nonlocal` is rare but legitimate. The most common real-world case is a closure that maintains state — a counter factory, a memoization wrapper, or a callback that accumulates results. Reaching for `global` in those situations would work technically, but it would pollute module scope with state that only one closure needs, which is a design smell.

What this looks like in practice

The rule of thumb for the interview: if the name you want to modify lives in another function's local scope, use `nonlocal`. If it lives at module level, use `global`. If you're not sure which one applies, you probably want a function argument or a return value instead. The Python docs on the nonlocal statement are explicit that `nonlocal` cannot reach module scope — trying to use it that way raises a `SyntaxError`.

Mutable globals look harmless until you confuse mutation with rebinding

Why lists and dictionaries are the exception that trips people up

When discussing Python global vs local variables, most explanations stop at integers and strings. The edge case that catches experienced candidates is mutable objects: lists, dictionaries, and sets. You can modify a global list or dictionary inside a function without declaring `global` — because you're not rebinding the name, you're mutating the object the name points to. Python's scope rules apply to name bindings, not to the objects themselves.

What this looks like in practice

`append` modifies the list object in place. The name `items` still points to the same object — nothing was rebound. `replace_items`, on the other hand, creates a brand-new local name that shadows the global for the duration of that call. The global list is untouched.

Why interviewers like this edge case

This is a precision test. The clean way to say it in an interview: "Mutation modifies the object; rebinding changes what name points to what object. Python's scope rules only apply to the binding, not the mutation." Candidates who learned the rule as "you always need `global` to change a global" will get this wrong. The correct rule is narrower: you need `global` to rebind a global name. Mutation of the object it points to is a different operation entirely. A real bug this pattern produces: a function that appends to a global list as a side effect, invisibly accumulating state across calls, making the function hard to test and the bug hard to find.

A better answer than 'just use global' is to avoid needing it

Why globals are often a smell, not a style choice

There are legitimate uses for module-level globals: constants (`MAX_RETRIES = 3`), configuration loaded once at startup, registry objects that are genuinely shared across the whole module. None of those involve rebinding the name at runtime. The problematic pattern is mutable shared state that gets modified by multiple functions — that's where globals break testability, make dependencies invisible, and create surprise behavior when call order changes.

In a python global variables interview, saying "I'd avoid it if I could" is actually a strong answer, not a dodge. It signals design awareness. The follow-up is always "what would you use instead?" — and you should have a concrete answer.

What this looks like in practice

The refactored version makes the dependency explicit. `process` takes the current total as an argument and returns the new one — you can test it in isolation with no setup. The class version encapsulates the state cleanly. Both are easier to reason about than a function that silently modifies a module-level variable. The Google Python Style Guide recommends avoiding mutable global state precisely because of the testing and readability costs.

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

Scope questions like this one feel simple until you're live on a call and the interviewer asks you to walk through the variable state line by line. The structural problem isn't knowledge — it's that most candidates have never explained this out loud under any pressure, so the first time they do, the explanation comes out tangled.

Verve AI Coding Copilot is built for exactly that gap. It reads your screen during live technical rounds and mock sessions, follows the specific problem you're working through, and surfaces targeted suggestions based on what you've actually written — not a generic hint bank. When you're debugging an `UnboundLocalError` on HackerRank or explaining scope behavior on a shared LeetCode screen, Verve AI Coding Copilot tracks the context of your current code and responds to what's actually happening in your session. It works across LeetCode, HackerRank, CodeSignal, and live technical screens, and the desktop app stays invisible to screen share at the OS level. The Secondary Copilot feature lets you stay focused on a single problem for an extended session — useful when an interviewer goes deep on one concept and you need to hold the thread without losing your place. If you want to practice explaining global scope, mutation vs rebinding, or the `nonlocal` distinction out loud before the real thing, Verve AI Coding Copilot runs mock interviews that respond to your actual answers, not a script.

FAQ

Q: What is the simplest interview-safe definition of a Python global variable versus a local variable?

A global variable is defined at module level, outside any function, and can be read from anywhere in that module. A local variable is created inside a function and only exists for the lifetime of that function call. The critical addition: reading a global from inside a function is always allowed, but assigning to a name inside a function makes Python treat that name as local unless you explicitly declare it global.

Q: Why does Python treat a variable as local when you assign to it inside a function?

Python performs static scope analysis when it compiles a function. If it sees any assignment to a name inside the function body, it classifies that name as local for the entire function — before any code runs. This is a compile-time decision, not a runtime one, which is why the error can fire on a line that appears before the assignment in the source code.

Q: What happens when a local variable has the same name as a global variable?

The local variable shadows the global for the duration of that function call. Inside the function, any reference to that name resolves to the local variable. The global is untouched and becomes visible again once the function returns. This is intentional behavior, not an error — but it can cause subtle bugs if you expect the global to be modified.

Q: Why do you get an UnboundLocalError when modifying a global inside a function without global?

Because Python has already classified the name as local (due to the assignment it found during compilation), so when the function tries to read the name before assigning a local value, it looks in the local namespace, finds the name classified as local but with no value yet, and raises `UnboundLocalError`. The global with the same name is not consulted — Python already decided it's not relevant to this scope.

Q: How does the global keyword work, and when should you use it?

Placing `global x` at the top of a function tells the interpreter to resolve `x` in module scope for both reads and writes throughout that function. Use it when you genuinely need to rebind a module-level name from inside a function. For constants or objects you're only reading, you don't need it. For mutable objects you're only mutating (appending, updating), you don't need it. Reserve `global` for the specific case of reassigning a module-level name.

Q: What is the difference between global and nonlocal in Python?

`global` reaches module scope — the top level of the file. `nonlocal` reaches the nearest enclosing function scope that is not module scope. Use `nonlocal` when you're in a nested function and need to modify a variable from the outer function. Use `global` when you need to modify a module-level variable. Trying to use `nonlocal` to reach module scope raises a `SyntaxError`.

Q: What is a better alternative to using global variables in real Python code?

The cleanest alternatives are function arguments and return values — make the dependency explicit rather than implicit. For state that needs to persist across multiple calls, a class instance is the natural container. For state shared only within a closure, `nonlocal` is cleaner than a module-level global. The guiding principle: if a piece of state is only relevant to one part of your program, don't let it leak into module scope.

Q: How would you explain this with a quick example if the interviewer asks for code?

Write a three-line example: a module-level `count = 0`, a function that does `count += 1` without `global`, and the resulting `UnboundLocalError`. Then add `global count` as the first line of the function and show that it works. That sequence — broken version, explanation of why, fixed version — covers definition, the scope rule, the error, and the fix in under 60 seconds of explanation.

Conclusion

You now have the short answer, the scope rule behind it, and enough edge-case fluency to handle whatever the interviewer reaches for next — mutable globals, `nonlocal`, the `UnboundLocalError` trace, or the design question about whether globals are even the right tool. None of that requires memorizing a longer script. It requires understanding one mechanism: assignment at compile time determines scope, and `global` is the explicit override.

Before your next session, say the 30-second answer out loud once. Then open a REPL and reproduce the `UnboundLocalError` example from scratch without looking. If you can do both, you're not just prepared for the question — you're prepared for the follow-up, which is where the point actually gets awarded.

JM

James Miller

Career Coach

Ace your live interviews with AI support!

Get Started For Free

Available on Mac, Windows and iPhone