2014-12-02 54 views
-1

我一直在研究这段代码一段时间。它口口声声说此:膳食生成器错误

Traceback (most recent call last): 

    File "N:\Computing\Meal Generator.py", line 30, in <module> 
    print(DaysOfTheWeek[0+counter],": ",Meals[random_meal]," and a number of ",NumberOfSides[random_meal],".") 

TypeError: unsupported operand type(s) for +: 'int' and 'str' 

这里是一个正在显示该错误的任何帮助将不胜感激的代码。

import random 
random.seed() 


Meals=[] 
SideDishes=[] 
DaysOfTheWeek=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"] 
print("1=Meal, 2=Side, 3=Finished") 
option=input("What would you like to do?: ") 
while option!=3: 
    if option=="1": 
     MealName=input("What meal would you like to add?: ") 
     NumberOfSides=input("How many sides would you like have with the meal?: ") 
     Meals=Meals,MealName,NumberOfSides 
    if option=="2": 
     SideName=input("What side would you like to add?: ") 
     SideDishes+=SideName 
    print("1=Meal, 2=Side, 3=Finished") 
    try_again=input("What else would you like to do?: ") 
    if try_again=="1": 
     option="1" 
    elif try_again=="2": 
     option="2" 
    else: 
     break 
print("Printing out meals for you") 
counter=1 
for counter in DaysOfTheWeek: 
    random_meal=random.randint(0,len(Meals)-1) 
    random_side=random.randint(0,len(SideDishes)-1) 
    print(DaysOfTheWeek[0+counter],": ",Meals[random_meal]," and a number of ",NumberOfSides[random_meal],".") 
    print("And the the side that will be served with will be: ",SideDishes[random_side]) 
    counter+=1 
print("Thanks for using the Meal-O-Matic") 

感谢您的帮助。 Tinymantwo

+0

你有没有读过错误信息?它告诉你'counter'是一个'str',因此'0 + counter'是没有意义的。您正在循环显示一系列字符串,例如'counter ==“星期一”'。 – jonrsharpe 2014-12-02 11:10:18

回答

0

您误解了循环在Python中的工作方式。

当你这样做for counter in DaysOfTheWeekcounter需要依次从DaysOfTheWeek每个值。这意味着它第一次将是“星期一”,然后是“星期”等,所以当你尝试将它添加到0时,它会因为该错误而失败。

但是你不应该把它添加到任何东西:这是关键。相反,这样做:

for day in DaysOfTheWeek: 
    ... 
    print(day, ": ", Meals[random_meal]," and a number of ",NumberOfSides[random_meal],".") 

,你不需要counter=0counter+=1

0

您正在使用Python像一个Javascript程序员:)

请这个东西是如何工作的Python阅读起来,一些提示:在条目列表的

  • for counter in ["asdf", "bla"]迭代,不在列表索引,所以counter"asdf""bla"
  • input返回一个字符串,所以while option != 3不会帮助你多少