String concatenation?

def change(s): s = s + "!" word = "holiday" change(word) print word 

how is it that the outcome of this is a "holiday" and not a "holiday!" Is it because 3 lines of codes are outside the function? If so, why does it matter if it is outside the function, since after the function changes?

+6
source share
5 answers

Try the following:

 def change(s): return s + "!" 

Use it as follows:

 word = 'holiday' print change(word) 

Or like this:

 word = 'holiday' word = change(word) print word 

Remember that any changes you make to the parameter string inside the function will not be visible outside the function, since the parameter s in the function is local to the scope of the function and any changes you make (for example, in the code in the question) will be visible only inside the function, not outside. All function parameters in Python are passed by value .

+6
source

You only change the local variable s in the change function. This does not change the word variable. If you want to change the 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 
+3
source

You are not returning a value from a shift.

Try:

 def change(s): s = s + "!" return s word = "holiday" word = change(word) print word 

So, in the above example, s is changed, and then the word is reassigned to the changed value.

+1
source

You pass a “copy” of the word, not an instance of the word, into the function. Therefore, the changes are applied to the copy of the word that you hold in the variable s inside the function

+1
source

s in change(s) is the name associated with the word value when calling change(word) .

On line s = s + "!" you bind s to a new line, which is created by concatenating the value bound to s and ! doing nothing for word .

It’s also better not to have side effects, even if it’s possible, so it’s better to return a new value.

 def change(s): return s + '!' 
+1
source

Source: https://habr.com/ru/post/913853/


All Articles