简体   繁体   English

关于while循环的问题。 我的代码有什么问题?

[英]Question on while loop. What's wrong with my code?

The question requires me to construct a while loop to display the values of the Rating of an album playlist stored in the list PlayListRatings given that the score is less than 6 and the list PlayListRatings is given by: PlayListRatings = [10, 9.5, 10, 8, 7.5, 5, 10, 10].这个问题需要我构建一个 while 循环来显示存储在列表 PlayListRatings 中的专辑播放列表的评分值,假设分数小于 6,并且列表 PlayListRatings 由以下公式给出: PlayListRatings = [10, 9.5, 10, 8、7.5、5、10、10]。

My code is我的代码是


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

NewPlayListRatings=[]


while(PlayListRatings[i]> 6):

    NewPlayListRatings.append(PlayListRatings[i])

    i=i+1
    

The output is [10, 9.5, 10, 8, 7.5] output 为 [10, 9.5, 10, 8, 7.5]

But the suggested answer shows this:但建议的答案表明了这一点:

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

The output is slightly different from mine. output 与我的略有不同。

[10 9.5 8 7.5 5] [10 9.5 8 7.5 5]

5 is included.包括5个。

Can someone enlighten me on what's wrong with my code?有人可以告诉我我的代码有什么问题吗? Thank you.谢谢你。

To start with I'm not sure how you even managed to get an output from your code considering that you do not define i before using it in your while loop declaration.首先,考虑到您在 while 循环声明中使用i之前没有定义它,我不确定您是如何设法从您的代码中获得 output 的。

Before referencing a value, in this case i , you must first declare that value.在引用一个值之前,在这种情况下i ,您必须首先声明该值。 This is what the accepted answer is doing on the second line with: i = 0 .这就是第二行接受的答案: i = 0

Now, your loop condition is while(PlayListRatings[i]> 6) if you were to translate this to english it would say "loop as long as PlayListRatings[i] is greater than 6 . When the loop reaches the value 5 , your loop condition becomes while(5 > 6) , and since it is not, the code inside of the loop is not executed and then the loop terminates. That is why the 5 is not in the final list.现在,您的循环条件是while(PlayListRatings[i]> 6)如果您要将其翻译成英文,它会说“只要PlayListRatings[i]大于6就循环。当循环达到值5时,您的循环条件变成了while(5 > 6) ,因为不是,所以循环里面的代码没有被执行,然后循环终止。这就是为什么 5 不在最终列表中的原因。

first of all its happens because you change the Rating variable before printing it and after checking it on while loop second, you think so hard!首先它的发生是因为您在打印之前更改了 Rating 变量,并且在第二个循环中检查了它之后,您想得太难了! it's like C language code!这就像 C 语言代码!

PlayListRatings = [10, 9.5, 10, 8, 7.5, 5, 10, 10]
[print(x) for x in PlayListRatings if x> 6]

or if you want to save the list或者如果你想保存列表

PlayListRatings = [10, 9.5, 10, 8, 7.5, 5, 10, 10]
new_list = [x for x in PlayListRatings if x> 6]
print(new_list)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM