我正在研究一個簡單的轉換器,並將所有轉換因子存儲在目錄中。它是接受來自和轉換,檢查,以確保它是可轉換,以及需要多少需要被轉換,然後出現了錯誤,此錯誤:數學目錄錯誤
Traceback (most recent call last):
File "python", line 20, in <module>
TypeError: string indices must be integers
的代碼(完時,活着就是這麼它不會永遠循環下去):
alive = 'yes'
while(alive == 'yes'):
doable = {'pint': ['cup', 'quart', 'galleon', 'pint'], 'quart': ['cup', 'quart', 'pint', 'galleon'], 'galleon': ['cup', 'quart', 'pint', 'galleon'], 'cup': ['cup', 'quart', 'galleon', 'pint', 'tbsp', 'tsp'], 'ounce': ['cup', 'tbsp', 'tsp', 'ounce', 'ml', 'liter', 'pound', 'gram', 'kilogram'], 'tbsp': ['cup', 'tbsp', 'tsp', 'ounce'], 'tsp': ['tsp', 'tbsp', 'cup', 'ounce'], 'ml': ['ml', 'ounce', 'liter'], 'liter': ['ml', 'ounce', 'liter'], 'pound': ['ounce', 'gram', 'kilogram', 'pound'], 'gram': ['ounce', 'gram', 'kilogram', 'pound'], 'kilogram': ['ounce', 'gram', 'kilogram', 'pound']}
pint = {'cup': 2, 'quart': 0.5, 'galleon': 0.125, 'pint': 1}
quart = {'cup': 4, 'quart': 1, 'galleon': 0.25, 'pint': 2}
galleon = {'cup': 16, 'quart': 4, 'galleon': 1, 'pint': 8}
cup = {'cup': 1, 'quart': 0.25, 'galleon': 0.0625, 'pint': 0.5, 'tbsp': 16, 'tsp': 48, 'ounce': 8}
ounce = {'cup': 0.125, 'tbsp': 2, 'tsp': 6, 'ounce': 1, 'ml': 30, 'liter': 0.0295735, 'pound': 0.0625, 'gram': 28.3495, 'kilogram': 0.0283495}
tbsp = {'cup': 0.0616115, 'tbsp': 1, 'tsp': 3, 'ounce': 0.5}
tsp = {'cup': 0.020833333, 'tbsp': 0.33333, 'tsp': 1, 'ounce': 0.166667}
ml = {'ml': 1, 'ounce': 0.033814, 'liter': 0.001}
liter = {'ml': 1000, 'ounce':33.8, 'liter': 1}
pound = {'ounce': 16, 'gram': 453.592, 'kilogram': 0.453592, 'pound': 1}
gram = {'ounce': 0.035274, 'gram': 1, 'kilogram': 0.001, 'pound': 0.00220462}
kilogram = {'ounce': 35.274, 'gram': 1000, 'kilogram': 1, 'pound': 2.2}
first = input("What would you like to convert from? ")
second = input("What would you like to convert to? ")
if(second in doable[first]):
amount = input("What is the amount of the first measurement? ")
conversion = first[second]
answer = float(amount) * float(conversion)
print("Your answer is: " + str(answer) + " " + second + "(s).")
else:
print("\nYOU CAN NOT CONVERT BETWEEN THESE TWO VARIABLES.")
alive = 'no'
任何想法,爲什麼它可能被示數,以及如何可以固定或其他方法來避免這個錯誤嗎?謝謝。
考慮閱讀錯誤信息,並考慮'第一個'在第二行的類型0. – Cairnarvon