# Coin flip + betting question

So im working on a challenge in the Python 3 course.

The task requires creating a coin-flip simulator, where the user can bet by stating their guess and their bet, then the function runs and returns a statement of heads/tails and the earnings/losses. The code I wrote works fine for this, and instead of simply stating what they lost/won I added/subtracted from their original money.

I wanted to go a bit further and have it update the money variable outside the function, out of curiosity. How would I go about doing that? As it stands, it restarts after each game, reusing the initial money value of 100.

``````import random

money = 100
Tails = 2
#Write your game of chance functions here
def coin_flip(guess, bet):
flip = random.randint(1, 2)
if flip == 1:
new_money = (money + bet)
print("Heads. You just won " + str(bet) + " dollars.  Your total money is " + str(new_money) + " dollars remaining.")
else:
loss = -1 * (bet)
new_money = (money + loss)
print("Tails. You just lost " + str(bet) + " dollars. Your total money is " + str(new_money) + " dollars remaining.")

#Call your game of chance functions here
``````

I was wondering if it had something to do with returning the values during the IF statement, but having only started Python on Wednesday, Iâ€™m rather confused.

1 Like

Discussed here.

2 Likes

You assigned the new money value to new_money in the function instead of money. So the moneys new value is put in new_money and money isnâ€™t changed, to fix this you need to assign the new money value to money.

That wonâ€™t work. If you try to use money as a variable in the function, youâ€™ll raise an UnboundLocalError.

``````money = 100

def more_money(x):
money = money + x

more_money(25)
print(money)
``````

Output:

``````Traceback (most recent call last):
...
money = money + x
UnboundLocalError: local variable 'money' referenced before assignment
``````

To make it work, you need to make money a global variable - a practice generally frowned upon - or make money a mutable type: list or dictionary.

``````money = [100]

def more_money(x):
money[0] = money[0] + x

more_money(25)
print(money)
``````

Output:

``````[125]
``````

Code is flawed: you can never win by guessing â€śTailsâ€ť.