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

Recommended Answers

All 2 Replies

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)

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])
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.