Reputation: 275
def change(s):
s = s + "!"
word = "holiday"
change(word)
print word
how come the output of this is "holiday" instead of "holiday!"? Is it because the 3 line of codes are outside the function? If so, why would it matter if it's outside the function since it's after the change function?
Upvotes: 6
Views: 300
Reputation: 236150
Try this:
def change(s):
return s + "!"
Use it like this:
word = 'holiday'
print change(word)
Or like this:
word = 'holiday'
word = change(word)
print word
Be aware that any modifications you do to a parameter string inside a function will not be seen outside the function, as the s
parameter in the function is local to the scope of the function, and any changes you do (like in the code in the question) will only be visible inside the function, not outside. All function parameters in Python are passed by value.
Upvotes: 6
Reputation: 133764
s
in change(s)
is a name that is bound to the value of word
when you call change(word)
.
In the line s = s + "!"
you are binding s
to a new string which is created by concatenating the value bound to s
and !
, not doing anything to word
.
Also it is best not to have side effects even if it is possible so returning a new value is better.
def change(s):
return s + '!'
Upvotes: 1
Reputation: 588
You are passing a 'copy' of word rather that word instance to the function. Therefore changes are applied to the copy of word you hold in s variable inside the function
Upvotes: 1
Reputation: 122536
You are only modifying the local variable s
in the function change
. This does not modify the variable word
. If you wish to modify word
, you need to return the result of change
and assign it to word
:
def change(s):
s = s + "!"
return s
word = "holiday"
word = change(word)
print word
Upvotes: 3
Reputation: 2460
You aren't returning the value from change.
Try:
def change(s):
s = s + "!"
return s
word = "holiday"
word = change(word)
print word
So in the above example, s is being modified, and then word is reassigned the modified value.
Upvotes: 1