我一直在研究这段代码。它一直这么说:
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 :(得分:0)
你误解了循环在Python中是如何工作的。
当您执行for counter in DaysOfTheWeek
时,counter
会依次从DaysOfTheWeek
获取每个值。这意味着第一次它将是&#34; Mon&#34;,然后&#34; Tue&#34;等等。因此,当您尝试将其添加到0时,它会因该错误而失败。
但你不应该把它添加到任何东西:这就是重点。相反,这样做:
for day in DaysOfTheWeek:
...
print(day, ": ", Meals[random_meal]," and a number of ",NumberOfSides[random_meal],".")
并且您不需要counter=0
或counter+=1
。
答案 1 :(得分:0)
你像使用Javascript程序员一样使用Python:)
请阅读这些内容如何适用于Python,一些提示:
for counter in ["asdf", "bla"]
遍历列表的条目,而不是列表索引,因此counter
将为"asdf"
和"bla"
input
会返回一个字符串,因此while option != 3
对您没有多大帮助