Please ignore secret bonuses. Secret tests do NOT award bonus. Max hw grade is 30+2 bonus efficiency

Do you need help?

In a function I want to return a modified variable that I created in another function that I have called.

_
_ginevra_ (620 points)
0 11 15
in HW2 required by (620 points)
Python does not allow me to, any suggestions?
372 views

1 Answer

S
Silktrader (2550 points)
2 6 16
by (2.6k points)

You could box your value in a mutable object — a list, a dictionary, or a class instance, among other options. You can then change the value inside the mutable instance you've passed to the function.

In other words, you wouldn't pass the immutable integer "number_of_letters" to your function, but possibly a "Game" object that contains it, a dictionary with such a key, etc.

We're often advised to use "pure" functions, ones which take arguments and return values, without side-effects (such as modifying a value).

_
_ginevra_ (620 points)
0 11 15
by (620 points)
What if the object to modify is a dictionary, it still bugs when I want to return the modified dictionary that I initialized and returned in the passed function. Do you know why?
angelo.spognardi (8170 points)
75 155 224
by (8.2k points)
Please, tomorrow during the lecture, remind me to consider this effect, so that I can clear your doubt that, I'm sure is shared among others.
S
Silktrader (2550 points)
2 6 16
by (2.6k points)

Woah, woah, wait! You probably don't want to re-initialise the dictionary within the function it's passed to. You would lose the reference to the original dictionary. The initialised one, within the function, would be a locally scoped dictionary, so changes would remain local and wouldn't show in the dictionary you meant to change originally.

I hope I understand your scenario — You created a dictionary, you want to pass it to a function which would then add, change or remove its entries.

You initialise your dictionary "example_dictionary" in a function named "ex1". You then call a function "change_dict" and pass "example_dictionary" to it. Within "change_dict" you won't repeat the initialisation, which looks like this:

example_dictionary = { "Ginevra": "Leodegrance" }

You will instead change or add its values with the index notation: 

example_dictionary["Ginevra"] = "Pendragon"

The alternatives are to use methods such as update().

_
_ginevra_ (620 points)
0 11 15
by (620 points)
Yes, that is the scenario indeed. I had actually changed its values in the way you have shown (except my scope was to subtract from the preexisting value which was an integer, an integer). However, when I attempted to return this dictionary in this function in which I have changed its values it says syntax error at the return line.
_
_ginevra_ (620 points)
0 11 15
by (620 points)
I actually realized that error has nothing to do with how I modified the dictionary but your comment was very much insightful so thank you.