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

medium
What is the output? SET x = 10. FUNCTION addFive(): SET x = 5. RETURN x + 5. OUTPUT addFive(). OUTPUT x.

Solution

  1. 1
    Step 1: The function creates a local variable x = 5 (separate from the global x = 10).
  2. 2
    Step 2: addFive() returns 5 + 5 = 10. First output: 10.
  3. 3
    Step 3: The global x is still 10 (unchanged by the function). Second output: 10.

Answer

10, then 10. The function's local x does not affect the global x.
Scope determines where a variable can be accessed. Local variables inside a function are separate from global variables with the same name. This prevents functions from accidentally modifying external state.

Example 2

hard
Explain why using global variables inside functions is generally discouraged.

Practice Problems

Try these problems on your own first, then open the solution to compare your method.

Example 1

medium
What is the output? SET y = 100. FUNCTION test(): OUTPUT y. test(). Will this work, or will there be an error?

Example 2

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

Background Knowledge

These ideas may be useful before you work through the harder examples.

function programmingreturn values