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
#5
if in the local scope you try to assign to a name that is not being declared global, then it will be local (that is what happening in the first snippet)
In the second snippet you assign to a and b, so they again are local names. For c, you don't assign to c, you assign new value to element with index 0. That's the difference, you don't create new name c within the local scope, so it uses the one from the global scope. see the difference

a = 20
b = 30
c = [1, 2, 3]
print(f'outside, id: {id(c)}, c:{c}')
def demo():
    a = 21
    b = 31
    c = [4, 5, 6]
    print(f'inside, id: {id(c)}, c:{c}')
    c[0] = 7
    print(f'inside, id: {id(c)}, c:{c}')
     
demo()
print(f'outside, id: {id(c)}, c:{c}')
Output:
outside, id: 139836028387528, c:[1, 2, 3] inside, id: 139836028387592, c:[4, 5, 6] inside, id: 139836028387592, c:[7, 5, 6] outside, id: 139836028387528, c:[1, 2, 3]
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Messages In This Thread
RE: Question regarding local and global variables - by buran - Apr-12-2020, 02:42 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Very Beginner question on simple variables Harvy 1 401 Apr-12-2024, 12:03 AM
Last Post: deanhystad
  It's saying my global variable is a local variable Radical 5 1,470 Oct-02-2023, 12:57 AM
Last Post: deanhystad
  Trying to understand global variables 357mag 5 1,290 May-12-2023, 04:16 PM
Last Post: deanhystad
  Delete all Excel named ranges (local and global scope) pfdjhfuys 2 2,224 Mar-24-2023, 01:32 PM
Last Post: pfdjhfuys
  Global variables or local accessible caslor 4 1,176 Jan-27-2023, 05:32 PM
Last Post: caslor
  global variables HeinKurz 3 1,284 Jan-17-2023, 06:58 PM
Last Post: HeinKurz
  How to use global value or local value sabuzaki 4 1,316 Jan-11-2023, 11:59 AM
Last Post: Gribouillis
  Clarity on global variables JonWayn 2 1,048 Nov-26-2022, 12:10 PM
Last Post: JonWayn
  Global variables not working hobbyist 9 4,989 Jan-16-2021, 03:17 PM
Last Post: jefsummers
  Global vs. Local Variables Davy_Jones_XIV 4 2,803 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