2

Example1:

x =[]
def func():

    print('x value is:', x)
    x.append('member1')
    print('x value is now:', x)
func()
print('x value is', x)

After run, the result will

('x value is:', [])
('x value is now:', ['member1'])
('x value is', ['member1'])

example2:

y = 50
def func():
    #global y
    print('y value is:', y)
    y = 2
    print('global y is change to:', y)
func()
print('y value is', y)

after run:

UnboundLocalError: local variable 'y' referenced before assignment

the solution is un-commment the line global x but why python treat list and interge in different way ? why list x don't require global? why python don't respond for example 1 for list like this:

local variable 'x' referenced before assignment

Thanks!

Niuya
  • 428
  • 1
  • 5
  • 14
  • 3
    Python isn't treating them differently, _you_ are. `x.append(...)` modifies the _list_. `y = ...` changes the value of the _variable_. If you try `x = []` (inside of the function) you'll get the exact same error. – Aran-Fey Jun 11 '17 at 11:49
  • Integers and lists *are* fundamentally different, too; the former is immutable, the latter is mutable. – jonrsharpe Jun 11 '17 at 11:54
  • to: Rawing: your answer may make sense,but what ever ```x.append(...)``` or ```x=``` , I think they are the same ? they are all changing/modifying the x ? when ```x.append(...)```, why python don't say```local variable 'x' referenced before assignment``` – Niuya Jun 11 '17 at 11:59
  • @Niuya: Python uses names similarly to people. I could tell someone to slap Niuya, and you would be slapped. If I then said that I'm now calling my oldest brother Niuya, that doesn't change who you are, it merely changes whom Niuya is referring to, Now slapping Niuya will slap my brother. .append is the slapping. It changes whatever object the name is referring to. Using x =, however just giving the name to something else without changing any object. – zondo Jun 11 '17 at 12:06
  • 1
    @Niuya You can think of a variable as a cup. The contents of the cup is the value of the variable. `x.append(...)` is like dipping a teabag into the cup - it changes the water in the cup to tea. But `x = ...` is like pouring away the water in the cup and replacing it with coffee. They're two entirely different things. – Aran-Fey Jun 11 '17 at 12:22

1 Answers1

0

Let's take this example.

y = 50
def func():
    print('y value is:', y)
func()
print('y value is', y)

Works fine. Why? You didn't modify the scope of the variable

When you reassigned y, you lost the reference to the global variable.

Also, when you write print('global y is change to:', y), that's not the global one since you just made it local

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245