-1

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() ```
  • Is this a trick question? Can't you just put `global money` at the top of `m`, like you did with `gm()`? – Random Davis Sep 28 '22 at 16:45
  • 1
    welp for some reason I put it at the top of m, and deleted it at some point. I must have forgot, and thought I had already done it. Sorry – OwenSucksAtCoding Sep 28 '22 at 17:09
  • 2
    In programming, there is no such thing as "it worked for a bit" - it worked *in a specific context*. In this case, it worked *for the `gm` function*, because *that's where you added the declaration*. If you want it to be a global variable in `m`, you must *also* declare `global` there. "global" isn't a property of the name `money`; it's a property of the *process of looking for* the name. Please see the linked duplicate for details. (since it also often comes up: it is also pointless to say that code "keeps doing" something - people often say this when they haven't *changed anything*, so....) – Karl Knechtel Sep 28 '22 at 17:09

1 Answers1

0

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 global amount won't have to be called repeatedly, as it is a relatively resource-expensive keyword.

Based on @Karl Knetchel's comment, note that:

Using global within a loop does not slow down the program. After a variable is declared as global once it is ignored by the compiler in future iterations. It is still a good idea to place global at the top of a function since this is just good programming practice (and avoids a global variable from being referenced before it is placed in the global scope), but it is not necessary.

Proof:

from time import time

money = 0
def single_global():
    init_time = time()
    global money
    for i in range(1000):
        money += 1
    return time() - init_time


def repeated_global():
    init_time = time()
    for i in range(1000):
        global money
        money += 1
    return time() - init_time

print(f"Time taken to increment to money after declaring it to be a global variable: {sum([single_global() for i in range(1000)])/1000}")
print(f"Time taken to increment to money, declaring it to be a global variable in each iteration: {sum([repeated_global() for i in range(1000)])/1000}")

Output:

Time taken to increment to money after declaring it to be a global variable: 0.0001020357608795166
Time taken to increment to money, declaring it to be a global variable in each iteration: 0.0001201772689819336
user17301834
  • 443
  • 1
  • 8
  • Aside from answering a question apparently caused by a typo (please read [answer]), this answer is incorrect on many levels. `global` is not a function at all and does not do anything at runtime (it is not "called"); it impacts on how code is compiled. While it's true that looking up global variables is less performant than using locals (at least in the reference implementation), this cost is already set once you decide to use a global; it doesn't matter *how*. Also, there is no function `g` in the original code. – Karl Knechtel Sep 28 '22 at 17:27