# Games of Chance exercise (Python 3) - global variables

Hi!

Question on the Games of Chance exercise (https://www.codecademy.com/practice/projects/games-of-chance):

Has anyone completed this? I’m still on the Heads/Tails function. I can make the function do the basics (take a guess and a bet, perform a random integer/coin flip, then add/subtract the bet from the money pot based on a random coin generator and print the results). However, the bit I’m stuck on is…the instructions also say:

`The project also has a variable named `money` that starts at `100`. This represents your current amount of money. In every game of chance, you will be able to bet money. The value of `money` should change depending on whether you win or lose the game.'

Any ideas on how to do this? I’ve read that you can’t change a variable that exists outside a function (global variable) within a function? i.e. i can use the variable ‘money’ within the function to perform calculations, but I can’t actually change what the value of ‘money’ is outside of the function. Am I missing something here?

You can use global variables. It’s just not always recommended because it can be hard to manage unexpected changes to it… but if you know what you’re doing and manage them well they are useful and necessary. For this problem they probably expect you to use a global variable. Consider how you can pass a parameter to function (as a possible technique to solve this).

There’s also a bit of subtlety in the following example. These aren’t the answers (can’t give that away) but notice how these things behave differently. It’s useful to pick up the variations along the way since they’ll sharpen your sense of what’s possible or not.

``````money = 100

def fun1():
money += 100
return money

fun1()
#UnboundLocalError: local variable 'money' referenced before assignment

def fun2():
more_money = money + 100
return more_money

fun2()
# >>> 200
fun2()
# >>> 200
fun2()
# >>> 200
# note that multiple calls don't change original "money" variable.
``````
1 Like

Great, thanks! This definitely helped me figure it out – used the former style but with the global keyword in the function! Perfect.

like this?

``````def some_function(money):
#code

some_function(money)
``````

Glad it helped though!