【问题标题】:The following python code is giving no output以下python代码没有输出
【发布时间】:2020-11-11 09:42:19
【问题描述】:
ingredients = ["chocolate", "vanilla", "strawberry"]

if "chocolate" in ingredients:
    if "marshmallow" in ingredients:
        print("Rocky Road")
elif "vanilla" and "strawberry" in ingredients:
    print("Neapolitan")

这应该打印出来

那不勒斯

但是终端没有输出。

你能帮帮我吗?

【问题讨论】:

  • 您误解了and 运算符的工作原理
  • 您误解了elif 条件的工作原理
  • 还要注意and的优先级高于in"vanilla" and "strawberry" = "strawberry";所以这条线只测试"strawberry" in ingredients

标签: python python-3.x list printing operators


【解决方案1】:

当“巧克力”在“成分”中时,您的 if/else 块将结束,因为条件结束。为了达成其他声明:

if "chocolate" in ingredients:

    if "marshmallow" in ingredients:

        print("Rocky Road")

if "vanilla" and "strawberry" in ingredients:

    print("Neapolitan")

试试这个。

【讨论】:

    【解决方案2】:
    if "chocolate" in ingredients and "marshmallow" in ingredients:
    
        print("Rocky Road")
    
    if "vanilla" in ingredients and "strawberry" in ingredients:
    
        print("Neapolitan")
    

    if "chocolate" in ingredients:
        if "marshmallow" in ingredients:
            print("Rocky Road")
    
    if "vanilla" in ingredients:
        if "strawberry" in ingredients:
            print("Neapolitan")
    

    【讨论】:

      猜你喜欢
      • 2019-07-17
      • 1970-01-01
      • 2019-05-05
      • 1970-01-01
      • 1970-01-01
      • 2012-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多