定义一个名为 food 的函数,它接收两个参数

Define a function named food which receives two parameters

它应该打印:

no food
breakfast,marmalade
breakfast,coffee
lunch,dessert
dinner
no food
no food
dinner,dessert
 def food(input,boolean):
    time = int(input)
    food_type = ""
    if time >= 0 and time < 6 or time >= 22:
        food_type = "no food"
    if time >= 6 and time <= 10:
        food_type = "breakfast"
    if time >= 11 and time <= 15:
        food_type = "lunch"
    if time >= 16 and time < 22:
        food_type = "dinner"
    dessert = ""
    if boolean == True and food_type == "breakfast":
        dessert = "marmalade"
    if boolean == False and food_type == "breakfast":
        dessert = "coffee"
    if boolean == True and food_type == "lunch":
        dessert = "dessert"
    if boolean == True and food_type == "dinner":
        dessert = "dessert"
    return ','.join((food_type, dessert)) 

基本上现在,我在 return '' 之间有一个逗号,所以它会打印 breakfast, marmalade 但是当涉及到 no food 时,它会在最后添加一个逗号,所以看起来像 no food,

它应该看起来像:

no food
breakfast,marmalade
breakfast,coffee
lunch,dessert
dinner
no food
no food
dinner,dessert

我不是 100% 确定你想要的输出,但我认为你不想有 dessert 或逗号,如果 food_type"no food" ,即使 booleanTrue。我至少可以想到两种不同的方法。

第一种方式是替换

    food_type = "no food"

    return "no food"

另一种方法是替换

  return ','.join((food_type, dessert))

  output = food_type
  if output != "no food":
    output = ','.join((food_type, dessert))
  return output

有些人更喜欢第二个,因为只有一个 return