In the following two functions, why is it that the first one can see the outside variable but the second one can not?

name = 'Jack'

def say_hello():
    print ('Hello ' + name + '!')

def change_name(new_name):
    name = new_name

I'm not sure about the question is, but try this code and see if it clarifies things.

name = 'Jack'
print '"name" is this memory address', id(name)

def say_hello():
    print ('Hello ' + name + '!')

def change_name(new_name):
    name = new_name
    print "name is now", name
    print '"name" is this memory address', id(name)

say_hello()
change_name("Joe")
print "after change name =", name
print '"name" is this memory address', id(name)

Edited 5 Years Ago by woooee: n/a

Another post is mine to StackOverflow as I got suprized why append works.

Normally the rule is simple: if you have global variable on left side of assignment (and only then method call does not count), you must write global variable at beginning of function in order for code to work.

It is generally recarded as bad programming style though, and you should pass variables to function instead. If parameter is mutable the change will go outside the scope of function, like list or dictionary.

data = ['Jack']

def say_hello(name):
    print ('Hello, ' + name + '!')

def change_name(new_name, data):
    data[0] = new_name

say_hello(data[0])
change_name('Peter', data)
say_hello(data[0])

Edited 5 Years Ago by pyTony: n/a

This article has been dead for over six months. Start a new discussion instead.