How to modify an 'external' object

Let’s say we have the variable money

money = 100

Now let’s say I have a function

def subtract_5(variable):
     return variable - 5

How can I get this above function to keep subtracting 5 instead of returning five minus the variable?

>>> 95
instead of:
>>> 95

Thank you

You can simply assign the result of the subtract_5 to the money variable:

money = 100

def subtract_5(variable):
    return variable - 5

for _ in range(5):
    money = subtract_5(money)

Output of this code:

1 Like

I meant every time the function is ran, money is subtracted by 5. So if I click run twice, money will now equal 90, three times, 85, and so on and so forth.

But in the codecademy environment every time you click Run or Save the code is executed in the isolated, fresh, new environment. So you can’t pass any values to the next execution frame (to the environment that will be created when you click Run again).

Ok, so if I called subtract 5 twice in one run, how can I get the money variable to be subtracted by 10 (calling the same function twice in one run)?

Here is the game I am playing

I don’t think you can do it in the Codecademy interface for this exercise, as it will not allow user input. It is actually fairly easy in a conventional Python environment that allows the use of an expression like "Play another game? y/n". See here for more discussion.

1 Like

Feed the result back into the function.

You could also create some form of box where you keep the money (a wallet, I suppose), and then create a function specifically for that wallet (this is exactly what a method is, a function bound to a specific object)

money = Wallet(100)
subtract = Wallet.subtract  # this method is bound to that wallet
print(money)  # 90

…but from what you’ve said so far, this seems like a reasonable solution:

money = money - 5

What behaviour is missing in that?

Say, for example that you want to bet 10 times.

money = 100
for _ in range(10):
    money += bet(7)  # add the difference caused by each bet

If the casino is supposed to have direct access to your bank account, then we’re back to the box strategy:

bank = BankAccount(100)
for _ in range(10):
    bet(bank, 7)  # they update the account for you

By all likelyhood the question is really about storing information outside the program. That’s what files are for.

1 Like

Ah! Yes, certainly if the user just wants to place 100 bets in advance, then it’s easy enough (and, of course, if random is indeed random, every bit as sensible as placing bets individually.)

This has been a frequent query, seen on several threads, and I have always assumed that it referred to placing individual bets, one following the other, something that is for some reason precluded by the interface. But I was perhaps hasty in making that assumption.

The only thing clear to me is that perspectives are confusing.