Python Forum
Question regarding local and global variables
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Question regarding local and global variables
#8
(Apr-12-2020, 02:44 PM)donmerch Wrote: So if I do this I see the inside and outside id of a & b are different even though I declared a & b global inside.

That is a good question. If you print the values again after demo() is called, you will see that the main values do change when assigned from within the function. But curiously, the ids are overwritten as well which seems to contradict the documentation.
a = 20
b = 30
c = [1, 2, 3]
print("before demo()",id(a),a, id(b),b, id(c),c)
 
def demo():
    global a
    global b
    a = 21
    b = 31
    c[0] = 5
    print("In demo()",id(a),a, id(b),b, id(c),c)
     
demo()
print("After demo()",id(a),a,id(b),b,id(c),c)
Output:
before demo() 140724845310816 20 140724845311136 30 1546429675272 [1, 2, 3] In demo() 140724845310848 21 140724845311168 31 1546429675272 [5, 2, 3] After demo() 140724845310848 21 140724845311168 31 1546429675272 [5, 2, 3]
Quote:id(object)
Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

The output does not show a unique and constant id.
Reply


Messages In This Thread
RE: Question regarding local and global variables - by TomToad - Apr-12-2020, 03:06 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Very Beginner question on simple variables Harvy 1 388 Apr-12-2024, 12:03 AM
Last Post: deanhystad
  It's saying my global variable is a local variable Radical 5 1,412 Oct-02-2023, 12:57 AM
Last Post: deanhystad
  Trying to understand global variables 357mag 5 1,264 May-12-2023, 04:16 PM
Last Post: deanhystad
  Delete all Excel named ranges (local and global scope) pfdjhfuys 2 2,123 Mar-24-2023, 01:32 PM
Last Post: pfdjhfuys
  Global variables or local accessible caslor 4 1,157 Jan-27-2023, 05:32 PM
Last Post: caslor
  global variables HeinKurz 3 1,267 Jan-17-2023, 06:58 PM
Last Post: HeinKurz
  How to use global value or local value sabuzaki 4 1,285 Jan-11-2023, 11:59 AM
Last Post: Gribouillis
  Clarity on global variables JonWayn 2 1,031 Nov-26-2022, 12:10 PM
Last Post: JonWayn
  Global variables not working hobbyist 9 4,928 Jan-16-2021, 03:17 PM
Last Post: jefsummers
  Global vs. Local Variables Davy_Jones_XIV 4 2,762 Jan-06-2021, 10:22 PM
Last Post: Davy_Jones_XIV

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020