Scope

Also known as: variable scope, local scope, global scope

definition

The region of a program where a variable is accessible. Understanding scope prevents bugs where you accidentally modify a variable you didn't intend to, or can't access one you expected.

๐Ÿ’ก Intuition

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.

Core Idea

Scope prevents name collisions. Two functions can each have a variable called 'count' without interfering with each other.

๐Ÿ”ฌ Example

x = 10 (global). def f(): y = 5 (local to f). Inside f, both x and y are visible. Outside f, only x is visible โ€” y doesn't exist.

๐ŸŽฏ Why It Matters

Understanding scope prevents bugs where you accidentally modify a variable you didn't intend to, or can't access one you expected.

โš ๏ธ Common Confusion

Modifying a global variable inside a function usually requires a special keyword (global in Python). Without it, you create a new local variable.

Related Concepts

How Scope Connects to Other Ideas

To understand scope, you should first be comfortable with function programming and return values.

Go Deeper

Frequently Asked Questions

What is Scope in CS Thinking?

The region of a program where a variable is accessible. Variables defined inside a function have local scope; variables defined outside have global scope.

Why is Scope important?

Understanding scope prevents bugs where you accidentally modify a variable you didn't intend to, or can't access one you expected.

What do students usually get wrong about Scope?

Modifying a global variable inside a function usually requires a special keyword (global in Python). Without it, you create a new local variable.

What should I learn before Scope?

Before studying Scope, you should understand: function programming, return values.