The region of a program where a variable is accessible. Variables defined inside a function have local scope and exist only within that function. Variables defined outside all functions have global scope and are accessible from anywhere in the program.
Scope is like rooms in a house. A variable created inside a room (function) can only be seen from inside that room. A variable in the hallway (global) can be seen from everywhere.
Showing a random 20 of 50 problems.
Example 1
medium
Why are global variables generally considered a bad design choice for sharing data between functions?
Example 2
medium
What single keyword added to `def add(n): total = total + n` (with global `total = 0`) lets it modify the global?
Example 3
medium
`def f(): n = n + 1` with global `n = 5`, no `global` declaration. What happens on `f()`?
Example 4
medium
`x = 1`. `def f(): x = 2; print(x)`. After `f()` and then `print(x)` outside, what prints (in order)?
Example 5
easy
`def f(n): return n + 1`. Is `n` local or global?
Example 6
medium
`def f(): x = 1; def g(): x = 2; g(); return x`. What does `f()` return?
Example 7
easy
`x = 10`. `def f(): print(x)`. What does calling `f()` print?
Example 8
challenge
Counter via default vs global: which keeps state between calls cleanly? `def f(): global c; c+=1` (with `c=0`) vs recreating a local each call.
Example 9
easy
Global `MAX = 100`. `def f(): print(MAX)`. What does `f()` print?
Example 10
hard
`x = 'A'`. `def outer(): x = 'B'; def inner(): x = 'C'; return x; return inner() + x`. What does `outer()` return?
Example 11
easy
A parameter `def f(n): ...`. Is `n` local or global to `f`?
Trace LEGB: `x = "global"`. `def outer(): x = "enclosing"; def inner(): return x; return inner()`. What does `outer()` return?
Example 14
medium
What is the output? SET y = 100. FUNCTION test(): OUTPUT y. test(). Will this work, or will there be an error?
Example 15
easy
`def f(): a = 5`. After calling `f()`, what is the value of `a` outside the function?
Example 16
medium
What is the output? Explain any errors.
SET count = 0
FUNCTION increment()
SET count = count + 1
SET bonus = 10
END FUNCTION
increment()
OUTPUT count
OUTPUT bonus
Example 17
hard
Explain why `def f(): x = x + 1` raises an error even though there is a global `x = 5`.
Example 18
easy
`x = 5` is defined outside any function. Inside `def f(): print(x)`, can f read `x`?
Example 19
easy
`g = 10`. `def f(): g = 20`. Without `global`, does `f()` change the outer `g`?
Example 20
easy
In Python's LEGB resolution order, what does the L stand for?