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

时间:2019-10-26 04:21:50

标签: python python-3.x python-3.7

它应该打印:

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时,它将在末尾添加一个逗号,因此看起来像{{1 }}

它看起来像:

no food,

1 个答案:

答案 0 :(得分:2)

我不确定要输出的内容是否100%,但是我想如果dessertfood_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