Python Scope of Variables with Example

Rules for variable scope in Python: Here, we are going to learn about the variable scopes i.e. which kind of variable can be accessed in which scope, the given example will show the scope of variable types of variables in Python. By IncludeHelp Last updated : September 17, 2023

Python Variables Scope

The variable scope defines the region in which it is accessible. In Python, the variables have mainly two scopes local and global.

Local Scope

A variable declared inside any function has the local scope of that function which means variable is accessible within the same function in which it is declared.

Global Scope

A variable declared outside of all functions (or, declared within the main body of the Python program) has the global scope to the program and it is accessible anywhere in the program.

Python program to demonstrate example of variable scopes

Here, we are implementing a Python program, that will show the rules about the variable scopes. In the example, we are using the global variable and location variable, accessing, changing their values within their scopes.

# Python code to demonstrate example 
# of variable scopes

# global variable
a = 100

# defining a function to test scopes
def func():
    # local variable
    b = 200

    # printing the value of global variable (a)
    # and, local variable (b)
    print("a: ", a, "b: ", b)
    
# main code
if __name__ == '__main__':
    # local variable of main
    c = 200
    
    # printing values of a, b and c
    print("a: ", a) #global 
    # print("a: ", b) #local of text *** will give an error
    print("c: ", c) # local to main
    
    # calling the function
    func()
    
    # updating the value of global variable 'a'
    a = a+10
    
    # printing 'a' again
    print("a: ", a) #global

Output

a:  100
c:  200
a:  100 b:  200
a:  110

Conclusion

A global variable can be accessed anywhere in the program, it's scope is global to the program, while a local variable can be accessed within the same block in which the variable is declared if we try to access a local variable outside of the scope – it will give an error.

Python Basic Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.