[Type A] Working with Functions – Chapter 3 Sumita Arora
Table of Contents
14. What do you understand by the local and global scope of variables? How can you access a global variable inside the function if the function has a variable with the same name?
Solution:
- Local scope refers to the visibility of variables within a function, while global scope refers to the visibility of variables throughout the entire program.
- To access a global variable inside a function with a variable of the same name, you can use the
global
keyword to declare the variable as global within the function.
Example Code:
Python
x = 10 # Global variable
def func():
global x # Declare 'x' as global
x = 20 # Access and modify the global variable 'x' within the function
print("Inside function:", x)
func()
print("Outside function:", x) # Output: 20