Python 打印时输入错误

Python Type Error while printing

我正在尝试转换伪代码;我收到类型错误,但我不确定为什么会收到此错误。我试过改变一些东西,但我不确定哪一点是错的。

  File "C:\Users\ClassyMelon\Downloads\mrocedures.py", line 46, in Menu
    DisplayWeight(Type, Weight, Volume)
  File "C:\Users\ClassyMelon\Downloads\mrocedures.py", line 24, in DisplayWeight
    print (str(Volume)), "g", "of", Metals[Type], "weighs",  Weight, "g"
TypeError: list indices must be integers or slices, not str

代码:

def GetVolume():
    print ("How many cubic cm of water does the item displace?")
    Volume = input("")
    while Volume == "":
       print ("You must input a value")
       Volume = input("")
return float(Volume)

def DisplayDensities():
    Densities = ["19.32", "10.49", "21.45"]
    Metals = ["Gold", "Silver", "Platimun"]
    for Counter in range(3):
        Msg = 'Density of ' + Metals[Counter]
        Msg = Msg + ' is ' + str(Densities[Counter]) + 'g per cubic cm'
        print (Msg)

def CalcWeight(Density, Volume):
     Weight = Density * Volume
     return Weight

def DisplayWeight(Type, Weight, Volume):
    WeightAsString = str(Weight)
    Metals = ["Gold", "Silver", "Platimun"]
    print (str(Volume)), "g", "of", Metals[Type], "weighs",  Weight, "g"

def Menu():
    DisplayDensities()
    print ("Choose an option Below:")
    print ("a) Calculate wieght of Gold")
    print ("b) Calculate wieght of Silver")
    Answer = input()
    Volume = GetVolume()
    if Answer == "a":
        Density = 19.32
        Type = "Gold"
    elif Answer == "b":
        Density = 10.49
        Type = "Silver"
    elif Answer == "b":
        Density = 21.45
        Type = "Platimun"    
    elif Answer !="a" or "b" or "c":
        print ("You must input 'a', 'b' or 'c'.")
        Menu()
    Weight = CalcWeight(Density, Volume)
    DisplayWeight(Type, Weight, Volume)
Menu()

 if __name__ == "__main__":
Menu()

Type 是一个字符串:实际上它已经是 "Gold"、"Silver" 或 "Platimun"(!) 之一。所以在由相同字符串组成的列表中查找它是没有意义的。

这行代码就是问题所在:

print (str(Volume)), "g", "of", Metals[Type], "weighs",  Weight, "g"

具体来说,是 Metals[Type] 部分。 Metals 是一个列表,列表通过整数索引访问,即 Metals[0]Metals[5]。但是在你的代码中,Type是一个字符串,你不能用字符串作为列表索引。