0

I have variables, say variables A outside the functions. In one function, mine_function, a random integer is added to the separate variables in variables A. But when I call the inv_function() after calling the mine_command(), the variables A stay 0. They were not added. What do I do?

P.S. this is from one file. The main file imports these functions to the main file to run.

import time as t
import random as rm

cobblestone = 0
coal = 0
ironOre = 0
ironIngot = 0
emerald = 0
diamond = 0
oak = 0
birch = 0
redwood = 0
spruce = 0
acacia = 0
jungle = 0
maple = 0
cash = 0

inventory = (cobblestone, coal, ironOre, ironIngot, emerald, diamond, oak, birch, redwood, spruce, acacia, jungle, cash)

def help_command():
  print('Here are all the available commands.')
  print("""1.'mine'
You mine underground to find various resources.
2.'sell'
Sell any item you wish.
3.'chop'
Chop down wood. Yay, deforestation!
4.'inv'
Shows your inventory
5.'balance'
Shows your total cash amount""")
  print('---------------------------------------------')




def mine_command():
  print('Mining...')
  t.sleep(5)

  cobblestoneC = rm.randint(64, 128)
  coalC = rm.randint(32, 64)
  ironOreC = rm.randint(16, 48)
  emeraldC = rm.randint(1, 3)
  chance = ('0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '3', '3', '3', '3', '3', '3', '5', '5', '5', '8')
  diamondC = rm.choice(chance)

  print("You obtained " + str(cobblestoneC) + " cobblestone, " + str(coalC) + " coal, " + str(ironOreC) + " iron ore, " + str(emeraldC) + " emerlad, and " + str(diamondC) + " diamond")

  cobblestone += cobblestoneC
  coal += coalC
  ironOre += ironOreC
  emerald += emeraldC
  diamond += diamondC
  
  print('---------------------------------------------')
ReplitUser
  • 87
  • 6

1 Answers1

0

This is due to ints being an immutable data type. When you modify them using the += operator, it replaces the entire variable, rather than modifying the existing one. This means that if you look at the variables inside the inventory tuple, they won't be changed, since they weren't updated.

You might want to consider using a dictionary data type to store your inventory, rather than a bunch of variables, since dictionaries are mutable.


inventory = {
  "cobblestone": 0,
  "coal": 0,
  # etc...
}

# To access items inside the dictionary
c = inventory["cobblestone"]

# To update them
inventory["coal"] = 4
inventory["cobblestone"] += 2

If you want to learn more about them, have a read of this page.

Miguel Guthridge
  • 1,444
  • 10
  • 27