我一直對這個問題感興趣已經兩天了。我是python和編程的新手,所以這種類型的錯誤的其他示例對我沒有太大的幫助。我正在閱讀列表和元組的文檔,但沒有找到任何有用的東西。任何指針都會很感激。沒有必要尋找答案,只是更多的資源在哪裏尋找。我正在使用Python 2.7.6。由於Python的列表索引必須是整數,而不是元組「
measure = raw_input("How would you like to measure the coins? Enter 1 for grams 2 for pounds. ")
coin_args = [
["pennies", '2.5', '50.0', '.01']
["nickles", '5.0', '40.0', '.05']
["dimes", '2.268', '50.0', '.1']
["quarters", '5.67', '40.0', '.25']
]
if measure == 2:
for coin, coin_weight, rolls, worth in coin_args:
print "Enter the weight of your %s" % (coin)
weight = float(raw_input())
convert2grams = weight * 453.592
num_coin = convert2grams/(float(coin_weight))
num_roll = round(num_coin/(float(rolls)))
amount = round(num_coin * (float(worth)), 2)
print "You have %d %s, worth $ %d, and will need %d rolls." % (num_coin, coin, amount, num_roll)
else:
for coin, coin_weight, rolls, worth in coin_args:
print "Enter the weight of your %s" % (coin)
weight = float(raw_input())
num_coin = weight/(float(coin_weight))
num_roll = round(num_coin/(float(rolls)))
amount = round(num_coin * (float(worth)), 2)
print "You have %d %s, worth $ %d, and will need %d rolls." % (num_coin, coin, amount, num_roll)
這是堆棧跟蹤:
File ".\coin_estimator_by_weight.py", line 5, in <module>
["nickles", '5.0', '40.0', '.05']
TypeError: list indices must be integers, not tuple
你不解析來自'raw_input'結果。它永遠不會是'2'。 –
既然你兩次寫了或多或少相同的源代碼,你應該考慮如何讓它更加優雅。事實上,你的onyl必須區分重量單位,如果需要轉換輸入,其餘的是相同的。 – OBu
OBu非常好。我將致力於完善我的代碼。我假設你正在談論製作一個功能。 – Aaron