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`?