Chapter 5: Problem 11
What is a variable’s scope?
Short Answer
Expert verified
Question: What is a variable's scope in programming and briefly explain the two main types of variable scopes with examples.
Answer: A variable's scope is the context in a program where a given variable can be accessed or used. It determines which parts of the code can access or modify the variable. The two main types of variable scopes are local and global. Local scope occurs when a variable is declared within a function or a block, and it can only be accessed within that function or block. For example:
```python
def some_function():
local_variable = 10 # This variable can only be accessed within this function
some_function()
```
Global scope occurs when a variable is declared in the main body of the code, outside of any function or block, making it accessible by any part of the code, including functions and blocks. For example:
```python
global_variable = 20 # This variable can be accessed by any part of the code
def some_function():
print(global_variable) # This function can access the global variable
some_function()
```
Understanding the difference between local and global scope is important for writing clean and maintainable code.