Computer Science – Programming concepts | e-Consult
Programming concepts (1 questions)
Local variables are declared inside a block of code, such as a function or a loop. They are only accessible within that specific block. Once the block of code finishes executing, the local variables are no longer accessible. They provide a way to store temporary data needed only within a particular part of the program.
Global variables are declared outside of any function or block of code. They are accessible from any part of the program. They are used to store data that needs to be shared and accessed by multiple functions or sections of the code. However, overuse of global variables can lead to code that is harder to understand and debug.
Example:
def my_function():
local_var = 10 # local variable
global_var = 5 # global variable
print("Inside function:")
print("Local variable:", local_var)
print("Global variable:", global_var)
my_function()
print("Outside function:")
print("Global variable:", global_var)
#print("Local variable:", localvar) # This would cause an error because localvar is not accessible outside my_function()