变量不会改变函数内的原始变量

The variables are not changing the original variables inside a function

我有变量,比如函数外的变量A。在一个函数 mine_function 中,一个随机整数被添加到变量 A 中的单独变量中。但是当我在调用 mine_command() 之后调用 inv_function() 时,变量 A 保留0. 没有添加。我该怎么办?

P.S。这是来自一个文件。主文件将这些函数导入主文件到运行.

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('---------------------------------------------')

这是因为 ints 是不可变数据类型。当您使用 += 运算符修改它们时,它会替换整个变量,而不是修改现有变量。这意味着如果您查看 inventory 元组中的变量,它们将不会更改,因为它们没有更新。

您可能要考虑使用字典数据类型来存储库存,而不是一堆变量,因为字典是可变的。


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

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

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

如果您想了解更多关于它们的信息,请阅读 this page