我是一名初學Python程序員,我正在創建一個卡路里計數器作爲實驗室。我想要做的是在列表中取出卡路里的整數值,並將其乘以列表中數量的整數值。試圖在兩個函數之間進行乘法運算?
的代碼可以在下面
找到我想要做的基本上是
calories = int((conv(carbs, "c") + conv(fats, "f") + conv(protein, "p") * qtyList[c]))
,但它說c
沒有定義(這是因爲我不這樣做在顯示列表功能,但我不知道如何將c合併到本地的addItem函數中,或者首先如何完成此工作。)
有關程序的更多信息和tl; dr以及它需要做什麼:
- 歡迎菜單
- 顯示選項
(a - add item, d - delete item, l - display list, q - quit)
時,它的
a
,接受字符串的項目名稱,INT項目數量,詮釋值轉化爲熱量,返回的熱量作爲一個int爲全局變量,然後乘以數量*卡路里項目總熱量d
- 通過其在列表中位置刪除列表中的項目- 顯示列表..簡單
q
- 退出
我很想知道,如果有人可以幫助我這個問題,雖然,而不是整個事情。謝謝。
# New Lab 7
# define lists
itemList = []
qtyList = []
calsList = []
totalCal = 0
def conv(grams, kind):
if kind == "f":
return grams * 9
else:
return grams * 4
def dispMenu():
print ("a - add item")
print ("d - delete the item")
print ("l - display the list so far")
print ("q - quit")
def addItem():
carbs = 0
fats = 0
protein = 0
calories = 0
item = input("Item name: ")
if item.isspace() or len(item) == 0:
print("item must have a proper name")
return None # get me outta here
try:
qty = int(input("quantity: "))
if qty <= 0:
print("quantity must be a positive number")
return None
except:
print("That was not a valid integer.")
return None
carbs = int(input("How many grams of carbs are displayed on your item? "))
fats = int(input("How many grams of fats are displayed on your item? "))
protein = int(input("How many grams of protein are displayed on your item? "))
global calories
calories = int((conv(carbs, "c") + conv(fats, "f") + conv(protein, "p") * qtyList[c]))
calsList.append(calories)
itemList.append(item)
qtyList.append(qty)
print("Your item contains", calories, "calories.")
global totalCal
totalCal += calories
return totalCal
def dispList():
if len(itemList) == 0:
print("\nThere are no items in your list\n")
else:
print("\n\n\nThe items in your list are")
print("Itm\tItem\t\tQty\tCals")
totalQty = int(0)
for c in range(len(itemList)):
print(str(c+1)+".\t" + itemList[c], "\t", qtyList[c])
totalQty += qtyList[c]
print("Total calories:\t{}".format(totalCal) + ".\n\n\n")
def delItem():
if len(itemList) == 0:
print("\nThere are no items in your list to delete\n")
else:
print("Please choose the item number to delete")
dispList()
choice = int(input("Delete item > "))
if 1 <= choice <= len(itemList):
del itemList[choice - 1]
del qtyList[choice - 1]
print("Item Deleted")
dispList()
else:
print("\nThe value is out of range\n")
# start the program
print("Welcome to Clinton's Calorie Counter!")
dispMenu()
while True:
choice = input("> ")
if choice == "a":
addItem()
dispMenu()
continue
elif choice == "q":
dispList()
print("Goodbye!")
break
elif choice == "l":
dispList()
dispMenu()
continue
elif choice == "d":
delItem()
continue
您可以將'c'作爲參數傳遞給函數。這是一個簡單的迴應,因爲我不明白'c'來自哪裏來自於 – maggick
c來自dispList函數,只要C不小於或等於0或大於商品列表 –
對您的代碼有太多評論。我認爲最好將它提交給http://codereview.stackexchange。com/ – sobolevn