【问题标题】:Meal Generator Error膳食发生器错误
【发布时间】:2014-12-02 11:07:53
【问题描述】:

我一直在研究这段代码。它一直在说:

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")

感谢您的帮助。 小二

【问题讨论】:

  • 阅读错误信息了吗?它告诉你counterstr,因此0+counter 没有意义。您正在遍历字符串列表,例如counter == "Mon".

标签: python python-3.x random syntax-error system


【解决方案1】:

您误解了 for 循环在 Python 中的工作原理。

当您执行for counter in DaysOfTheWeek 时,counter 依次从DaysOfTheWeek 获取每个值。这意味着第一次它将是“星期一”,然后是“星期二”,等等。所以当你尝试将它添加到 0 时,它会失败并出现该错误。

但你不应该将它添加到任何东西:这就是重点。相反,请这样做:

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

您不需要counter=0counter+=1

【讨论】:

    【解决方案2】:

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

    请阅读这些东西在 Python 上的工作原理,一些提示:

    • for counter in ["asdf", "bla"] 迭代列表的条目,而不是列表索引,所以counter 将是"asdf""bla"
    • input 返回一个字符串,所以 while option != 3 对你没有多大帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-10
      • 1970-01-01
      • 2021-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多