How do I fix "local variable 'money' referenced before assignment?
Question:
So I was making an Idle Miner-type game, and I’m trying to make an upgrade. When I wanted to make it so that when you buy said upgrade, your money goes back to zero, but then I got the error. I had it before, so I put global money
. I thought this would fix it, and it did for a bit. Here’s the code
import time
import math
money = 0
amount = 1
print("Upgrades will occur at:")
print("10 dollars")
print("50 dollars")
print("100 dollars")
print("100 dollars")
print("1000 dollars")
print("10,000 dollars")
print("1,000,000 dollars")
print("")
def gm():
global money
money = money + amount
print("You have " + str(money) + " dollars!")
time.sleep(1)
def m():
while True:
gm()
if money == 10:
upg1 = input("Would you like to buy a multiplier? y for yes, n for no ")
if upg1 == "y":
global amount
amount = amount + 1
print("")
print("ACHIEVEMENT!: Baby's first upgrade")
print("")
money = 0
time.sleep(2)
else:
print("You will have a chance to buy this again :)")
m() ```
Answers:
As @Random Davis pretty much said, the only problem is that you forgot to include global money
at the top of function m
similarly to how you included it in gm
.
Also I recommend positioning global amount
outside the while loop in the function m
to optimise you program, ensuring that the keyword global
won’t have to be called repeatedly, as it is a relatively resource-expensive keyword.
So I was making an Idle Miner-type game, and I’m trying to make an upgrade. When I wanted to make it so that when you buy said upgrade, your money goes back to zero, but then I got the error. I had it before, so I put global money
. I thought this would fix it, and it did for a bit. Here’s the code
import time
import math
money = 0
amount = 1
print("Upgrades will occur at:")
print("10 dollars")
print("50 dollars")
print("100 dollars")
print("100 dollars")
print("1000 dollars")
print("10,000 dollars")
print("1,000,000 dollars")
print("")
def gm():
global money
money = money + amount
print("You have " + str(money) + " dollars!")
time.sleep(1)
def m():
while True:
gm()
if money == 10:
upg1 = input("Would you like to buy a multiplier? y for yes, n for no ")
if upg1 == "y":
global amount
amount = amount + 1
print("")
print("ACHIEVEMENT!: Baby's first upgrade")
print("")
money = 0
time.sleep(2)
else:
print("You will have a chance to buy this again :)")
m() ```
As @Random Davis pretty much said, the only problem is that you forgot to include global money
at the top of function m
similarly to how you included it in gm
.
Also I recommend positioning global amount
outside the while loop in the function m
to optimise you program, ensuring that the keyword global
won’t have to be called repeatedly, as it is a relatively resource-expensive keyword.