我试图转换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()
'Metals'是一个列表,'Type'是一个字符串 - 你期望'Metals [Type]'要做什么?另外,你应该真的阅读样式指南:http://www.python.org/dev/peps/pep-0008/ – jonrsharpe
stacktrace很明确:你写了'Metals [Type]',但'Type'是一个字符串并应该是一个整数。 – Delgan