Scope Examples in CS Thinking
Start with the recap, study the fully worked examples, then use the practice problems to check your understanding of Scope.
This page combines explanation, solved examples, and follow-up practice so you can move from recognition to confident problem-solving in CS Thinking.
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.
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.
Read the full concept explanation →How to Use These Examples
- Read the first worked example with the solution open so the structure is clear.
- Try the practice problems before revealing each solution.
- Use the related concepts and background knowledge badges if you feel stuck.
What 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.
Sense of Study hint: When debugging a scope issue, ask: where was this variable defined? If inside a function, it only exists while that function runs. If you need to share data between functions, pass it as a parameter and return the result rather than relying on global variables.
Worked Examples
Example 1
mediumAnswer
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 these problems on your own first, then open the solution to compare your method.
Example 1
mediumExample 2
mediumExample 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
challengeRelated Concepts
Background Knowledge
These ideas may be useful before you work through the harder examples.