Home » Python » Python programs

Python program to demonstrate variables scope

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.
Submitted by IncludeHelp, on August 06, 2019

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.

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 code to demonstrate example of variable 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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.