Q:

Python program to demonstrate variables scope

0

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.

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now