I have a question about the print_first_word and print_last_word function in ex25.
In this function, whatever varies i entered, it will cut the first or last word and return the varies (“words” in this example) back to the global environment. I am confused because in these two functions, i didn’t return the varies “function” back to the global environment. All the changes about “words” should remained within the function. Isn’t it?
I believe I’ve answered this a few times, but your surprise is mostly a misunderstanding of how a variable is passed to a function. Generally there are two styles: pass by value and pass by reference. Pass By Value (PBV) takes a variable you give to a function and makes a copy of it, that way the function can’t change the variable in the caller. That’s how you believe python should work.
Python however is doing a pass by reference (PBR), which means you are only getting a reference to the variable, not a copy of it. There is only one copy of the list, but you are accessing it with two names. One name is outside the function, and another is inside the function. But, those two names still access the one copy of the list, so when your function runs it alters the single copy.
If you want to prevent this, then you need to copy the list with
[:], but then you’re sort of being inefficient.
I have a problem in ex25 I am unable to call the last two functions ex25.sort_sentence(sentence) and ex25.print_first_and_last(sentence) I looked for error severla times but failed to find please help…
the error mentioned is module ‘ex25’ has no attribute ‘sort_sentence’ and same for the last one
okay my mistake a spelling mistake there ? its sentence not sentences
Any time you see that error it’s most likely a spelling mistake.