2015-11-03 49 views
-3

我试图转换psuedocode;我有一个类型错误,但我不知道为什么我得到错误。我试过改变一些东西,但我不确定哪一点是错的。Python类型打印时出错

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

'Metals'是一个列表,'Type'是一个字符串 - 你期望'Metals [Type]'要做什么?另外,你应该真的阅读样式指南:http://www.python.org/dev/peps/pep-0008/ – jonrsharpe

+0

stacktrace很明确:你写了'Metals [Type]',但'Type'是一个字符串并应该是一个整数。 – Delgan

回答

2

这行代码的问题是:

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

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

+0

此答案不包含任何不在追踪中的信息! – jonrsharpe

+1

...显然OP没有*了解*追踪,所以你想要做什么? –

+0

但是,你实际上并没有解释*任何东西,你使用的错误信息基本上是相同的单词;如果OP不了解追溯,他们为什么会理解这一点? – jonrsharpe

0

类型是串:(!),其实它已经是 “金”, “银” 或 “Platimun” 之一。因此,在由相同字符串组成的列表中查找它是没有意义的。