[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
"Spread the light within, illuminate the hearts around you. Sharing is not just an action, but a sacred journey of connecting souls."~ Anonymous

Leave a Reply

Your email address will not be published. Required fields are marked *