Search code examples
pythonvariables

I Have a Function Loading a Value From a File, but It Isn't Working


gold = 0
def load_gold():
  e = open('gold.txt', 'r')
  ee = e.readline()
  gold = int(ee)
load_gold()

In the file, the only information is

-1

The saving function works just fine, but whenever I reload and run the program, it resets gold to 0.


Solution

  • gold is declared as a global variable so if you want to alter it in your method you need declare is global in the method. Like this:

    gold = 0
    def load_gold():
        global gold
        e = open('gold.txt', 'r')
        ee = e.readline()
        gold = int(ee)
    load_gold()