English

Differentiate between the following with the help of an example: Global and Local variable - Computer Science (Python)

Advertisements
Advertisements

Question

Differentiate between the following with the help of an example:

Global and Local variable

Distinguish Between

Solution

In Python, a variable that is defined outside any function or any block is known as a global variable. It can be accessed in any function defined in the program. Any change made to the global variable will impact all the functions in the program where that variable is being accessed.

A variable that is defined inside any function or block is known as a local variable. It can be accessed only in the function or a block where it is defined. It exists only till the function executes.

Program:
# Global Variable
a = "Hi Everyone!!"
def func():
    # Local variable
    b = "Welcome"
    # Global variable accessed
    print(a)        
    # Local variable accessed
    print(b)        
func()
# Global variable accessed, return Hi! Everyone
print(a)
# Local variable accessed, will give error: b is not defined
print(b)  
shaalaa.com
Scope of a Variable
  Is there an error in this question or solution?
Chapter 7: Functions - Exercise [Page 170]

APPEARS IN

NCERT Computer Science [English] Class 11
Chapter 7 Functions
Exercise | Q 6. b) | Page 170
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×