Working with Functions — Question 14
Back to all questionsLocal scope — Variables defined within a specific block of code, such as a function or a loop, have local scope. They are only accessible within the block in which they are defined.
Global scope — Variables defined outside of any specific block of code, typically at the top level of a program or module, have global scope. They are accessible from anywhere within the program, including inside functions.
To access a global variable inside a function, even if the function has a variable with the same name, we can use the global keyword to declare that we want to use the global variable instead of creating a new local variable. The syntax is :
global<variable name>
For example:
def state1():
global tigers
tigers = 15
print(tigers)
tigers = 95
print(tigers)
state1()
print(tigers)In the above example, tigers is a global variable. To use it inside the function state1 we have used global keyword to declare that we want to use the global variable instead of creating a new local variable.