【发布时间】:2022-01-18 20:16:17
【问题描述】:
我正在编写一个代码,用户应该选择要吃的肉,然后随机分配其他食物来完成一顿饭。循环应该向您显示您拥有的物品,并且在循环结束时应该打印出总卡路里值。我编写了整个程序,但是当我提示用户吃肉时,它会停止并且不会进入 while 循环。这是程序:
import random
usermeal = []
meatcalories = 0
fruitcalories = 0
vegcalories = 0
desertcalories = 0
#defining a list of different foods...
meats = {"NY Strip": 300, "Shrimp": 100, "Lobster": 200, "Clams": 300, "Scallops": 200}
vegetables = {"Asparagus": 50, "Potato": 80, "Brocoli": 50, "Kale": 30, "Beans": 40}
fruits = {"Apple": 40, "Orange": 30, "Bananna":45, "Kiwi": 40, "Mango": 40}
deserts = {"Ice cream":300, "Brownie": 400, "Cookie": 200, "Chocolate":300, "Candy": 100}
print("We are going to make you a meal today. Each meal will have one item from each food category:")
print(meats)
print(vegetables)
print(fruits)
print(deserts)
print("Start by choosing one of the meats")
meatchoice = input("Please choose the meat that you want: ")
while len(usermeal) == 4:
#prompt the user for their meat decision
if meatchoice not in meats:
print("Please choose a meat from the options!")
meatchoice = input("Please choose the meat that you want: ")
if meatchoice in meats:
usermeal.append(meatchoice)
meatcalories = meats.get(meatchoice)
print("This is your meal so far", usermeal)
#randomly chooses a vegetable
print("Now lets get the vegetable!")
random_veg = random.choice(list(vegetables))
print("The random vegetable is:", random_veg)
usermeal.append(random_veg)
vegcalories = vegetables.get(random_veg)
print("This is your meal so far,", usermeal, "and its calorie count:", vegcalories)
#randomly chooses a fruit
print("Now lets get the fruit!")
random_fruit = random.choice(list(fruits))
print("The random fruit is:", random_fruit)
usermeal.append(random_fruit)
fruitcalories = fruits.get(random_fruit)
print("This is your meal so far,", usermeal, "and its calorie count:", fruitcalories)
#randomly chooses a desert
print("Now lets get the desert!")
random_desert = random.choice(list(deserts))
print("The random desert is:", random_desert)
usermeal.append(random_desert)
desertcalories = deserts.get(random_desert)
print("This is your meal so far,", usermeal, "and its calorie count:", desertcalories)
print("Now since we have all the foods, lets see how many calories it is")
totalcals = meatcalories + vegcalories + fruitcalories + desertcalories
print("Total Calorie Count: ", totalcals)
我不确定问题出在哪里。我知道它真的很小。如果有人可以向我指出,我将不胜感激。请显示代码中的更改。提前致谢!
【问题讨论】:
标签: python list dictionary while-loop