Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

concatenating strings?

Tags:

python

string

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?

like image 273
alicew Avatar asked Apr 22 '12 17:04

alicew


2 Answers

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.

like image 54
Óscar López Avatar answered Sep 28 '22 17:09

Óscar López


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
like image 32
Simeon Visser Avatar answered Sep 28 '22 19:09

Simeon Visser