如何在列表python中打印项的字符串版本


def calorie():
protein = 0
fat = 0
carb = 0
tlist = [protein, fat, carb]
for i in tlist:
print('Enter food ' +  str(i))
i = input()
print(protein)
print(carb)
print(fat)
calorie()

现在它打印"输入食物0"我想让它循环,每次都询问蛋白质、脂肪和碳水化合物,然后保存下来,这样我以后就可以把它放进数据库了。我现在的代码是4个不同的def,指向蛋白质,然后是碳水化合物等等,但经过思考,我认为只在一个def中循环会更容易,但我无法使其工作。非常感谢

它打印enter food 0,因为通过编写for i in tlist,您不是在迭代这些变量的名称,而是在迭代它们的值。proteinfatcarb的值均为0,这就是Python打印的值。

试着用字典?

calorie = {'protein': 0, 'fat': 0, 'carb': 0}
for key in calorie:
value = input(f"Enter value of {key}: ")
calorie[key] = int(value)

do you wan't tlist = ['protein', 'fat', 'carb'] this thing as a loop and you will enter how much amount specific things present in food.

def calorie():
protein = 0
fat = 0
carb = 0

u=input("enter food name") #here you type food which detailed you wana insert.
tlist = ['protein', 'fat', 'carb']
for i in tlist:
s=input("enter {} value in gm".format(i))
print(f" {u} has {s} gm of {i}") #here it print amount nutrient the food has

i hope it will resolve your problem

最新更新