打印时Python类型错误

时间:2015-11-03 17:31:07

标签: python typeerror

我试图转换伪代码;我收到了类型错误,但我不确定为什么我会收到错误。我尝试过改变一些事情,但我不确定哪一点是错的。

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

2 个答案:

答案 0 :(得分:2)

这行代码是问题所在:

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

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

答案 1 :(得分:0)

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