What is a global variable in Python?

What is a global variable in Python?

a) A variable that can only be used in a loop
b) A variable that is accessible throughout the entire program
c) A variable that is only accessible within a function
d) A variable that stores a list of global functions

Answer:

b) A variable that is accessible throughout the entire program

Explanation:

A global variable in Python is a variable that is accessible throughout the entire program, including inside functions. Global variables are defined outside of any function or block, and they maintain their values throughout the program’s execution.

x = 10  # Global variable

def my_function():
    print(x)  # Accessing the global variable

my_function()  # Prints 10

Global variables are useful when you need to share data across different parts of your program. However, they should be used with caution, as they can lead to code that is harder to understand and maintain, especially in larger programs.

To modify a global variable inside a function, you must use the global keyword to indicate that the variable is global.

Leave a Comment

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

Scroll to Top