Scope Examples: 45 Problems with Answers
Worked examples of Scope to try before you open each solution, then practice problems with answers.
Worked Examples
Example 1
mediumShow solution
Answer
First step
See the full worked solution + why-it-works coaching
SetupKey insightWhy it worksCommon pitfallConnection
Example 2
hardExample 3
mediumExample 4
hardExample 5
hardPractice Problems
Try each one, then open the solution to compare your method.
Example 1
mediumExample 2
mediumSET count = 0
FUNCTION increment()
SET count = count + 1
SET bonus = 10
END FUNCTION
increment()
OUTPUT count
OUTPUT bonus
Example 3
easyExample 4
easyExample 5
easyExample 6
easyExample 7
easyExample 8
easyExample 9
easyExample 10
easyExample 11
mediumExample 12
mediumExample 13
mediumExample 14
mediumExample 15
mediumExample 16
mediumExample 17
mediumExample 18
mediumExample 19
mediumExample 20
challengeExample 21
challengeExample 22
challengeExample 23
easyExample 24
easyExample 25
easyExample 26
easyExample 27
easyExample 28
mediumExample 29
mediumExample 30
mediumExample 31
mediumExample 32
mediumExample 33
mediumExample 34
mediumExample 35
mediumExample 36
mediumExample 37
hardExample 38
hardExample 39
hardExample 40
challengeWhat to focus on
Core idea: Scope prevents name collisions. Two functions can each have a variable called 'count' without interfering with each other.
Common stuck point: Modifying a global variable inside a function usually requires a special keyword (global in Python). Without it, you create a new local variable.
Ask yourself: Does the answer depend on whether a name created inside a function can be seen or changed from somewhere else?
Concept recap
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.
Each function is a room with one-way glass. From inside, you can look out and read the notices on the hallway board, the globals; from the hallway, nobody can see into the room. Writing a name inside the room pins a new note on the room's own wall rather than changing the hallway board, unless you declare global.
Read the full lesson on ScopeRelated concepts
Background knowledge
These ideas may be useful before you work through the harder examples.