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; variables defined outside have global scope.
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.
Worked Examples
Example 1
mediumSolution
- 1 Step 1: The function creates a local variable x = 5 (separate from the global x = 10).
- 2 Step 2: addFive() returns 5 + 5 = 10. First output: 10.
- 3 Step 3: The global x is still 10 (unchanged by the function). Second output: 10.
Answer
Example 2
hardPractice Problems
Try these problems on your own first, then open the solution to compare your method.
Example 1
mediumExample 2
mediumRelated Concepts
Background Knowledge
These ideas may be useful before you work through the harder examples.