【问题标题】:python : why it is not printingpython:为什么它不打印
【发布时间】:2021-08-12 17:44:14
【问题描述】:
PlayListRatings = [10, 9.5, 10, 8, 7.5, 5, 10, 10]
i=0
score=PlayListRatings[0]
while (i < len(PlayListRatings) and score<6):
    score=PlayListRatings[i]
    print(score)
    i=i+1

编写一个while循环来显示存储在列表PlayListRatings中的专辑播放列表的Rating值。如果分数小于 6,则退出循环。 PlayListRatings 列表由以下给出:

PlayListRatings = [10, 9.5, 10, 8, 7.5, 5, 10, 10]

不打印任何东西

【问题讨论】:

    标签: python loops


    【解决方案1】:

    正如其他人所说,您的代码将在第一次迭代时失败,因为它不小于 6。

    相反,您应该将score &lt; 6 更改为score &gt;= 6 并使用PlayListRatings[i] 而不是score

    改变得分条件将符合以下陈述:

    如果分数小于6,则退出循环。

    此外,我们必须使用PlayListRatings[i] 而不是score,因为score 最终会落后一个元素。这是因为 score 仅在 while 循环中更新。 您也可以通过将score=PlayListRatings[i] 更改为score=PlayListRatings[i + 1] 并将其放在print(score) 下方来解决此问题。

    通过这些更改,您的代码将如下所示:

    PlayListRatings = [10, 9.5, 10, 8, 7.5, 5, 10, 10]
    i = 0
    while (i < len(PlayListRatings) and PlayListRatings[i] >= 6):
        print(PlayListRatings[i])
        i += 1
    

    【讨论】:

    • score 在测试后打印前更新。
    • @tobias_k 更新了答案,不打印 6 分以下的第一个分数,感谢您了解
    【解决方案2】:

    您的循环中的条件倒退了:您希望循环停止一次score &lt; 6,而不是继续while 条件成立!您可以将该位更改为&gt;= 6,但您也必须更改循环的主体,否则它仍会打印第一个分数&lt; 6。以下是一些选项,所有选项都没有索引变量:

    • 使用break:

      for score in PlaylistRating:
          if score < 6:
              break
          print(score)
      
    • 使用itertools.takewhile:

      for score in itertools.takewhile(lambda x: x >= 6, PlayListRatings):
          print(score)
      
    • 使用iternext(默认)和:=(3.8 及更高版本)

      it = iter(PlayListRatings)
      while (score := next(it, -1)) >= 6:
          print(score)
      

    【讨论】:

      【解决方案3】:
      score<6
      

      False,所以while 循环永远不会开始。

      【讨论】:

        【解决方案4】:

        score = 10 不是

        【讨论】: