Global vs Globals in Python

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

Program 1

#global Key word and Global vs Globals()
# a=100 
# def display():
#      global a
#      a=a+10
#      print(a)   # 110
# def show():
#     global a
#     print(a)    #110
#     a=a-50
# def abc():
#     global a
#     print(a)  # 60
# #calling 
# display()
# show()
# abc()

a=20  # Global
b=10  # Global
def display():
    a=100 # Local
    b=50  # Local
    print("Local in display: ",a)
    print("Local in display: ",b)
    # print("global in display: ",globals()['a'])
    # print("global in display: ",globals()['b'])
    x=globals()['a']
    x=x+10
    y=globals()['b']
    y=y+10
def show():
    print("global in show: ",a)
    print("global in show: ",b)

# Calling
display()
show()

 

Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google

courses
Image

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *