我是一名初学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