HomePagev2 Forums Python Discussions Understanding global scope

  • Satish Vadlamani

    Administrator
    September 3, 2020 at 2:22 am

    In the below code the function func() does not print 10 although we use the same variable name temp inside the function. That is because the temp inside the function has a local scope.

    temp = 10 	 # global-scope variable
    
    def func():
          temp = 20   # local-scope variable
          print(temp)
    
    print(temp) 	 # output => 10
    func() 		 # output => 20
    print(temp) 	 # output =>10 

    In order for python to read print 10 even from inside the function we use the keyword global. Below code explains that better.

    temp = 10 	 # global-scope variable
    def func():
       global temp # this tell python that the variable outside the function is the same as variable inside.
       temp = 20 # local-scope variable
       print(temp)
    
    print(temp) # output => 10
    func() # output => 20
    print(temp) # output => 2
  • Sai Gowtham Babu AMBURI Gowtham Babu AMBURI

    Member
    September 10, 2020 at 4:46 am

    Thank you for the small explanation @satishvadlamani sir

  • Badri Rajasekhar Reddy Rajasekhar Reddy

    Member
    September 10, 2020 at 6:32 am

    Thank you for the small explanation about local-scope and global-scope variables@satishvadlamani

Log in to reply.

Original Post
0 of 0 posts June 2018
Now