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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With