Home > Software engineering >  While loop output explanation
While loop output explanation

Time:03-11

new learner, unable to under stand the output of the following program.

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

Output

10
10
9.5
10
8
7.5

why 10, 10 are together? why there is third 10? why didn't wile loop break on 5?

CodePudding user response:

If you move i = i 1 statement in while loop one line up, your code will be working correctly.

CodePudding user response:

First will split out individual lines so that it will be easy for you to understand.

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

Here you declared an ARRAY of numbers, whenever you pick the 0th index of the array will become 10.

i = 0 // Here you declared an iterator with an initial value 0

Rating = PlayListRatings[0] As I said, here in this line Rating variable initialization will have the value 10 as it is the 0th index of Array

while(i < len(PlayListRatings) and Rating >= 6):
    print(Rating)
    Rating = PlayListRatings[i]
    i = i   1

So, In the loop, the initial condition will be the iterator i less than 8 (total length of the Array) AND Rating greater than or equal to 6 of course it is as it contains the 0th index value 10 from the Array. So that this loop will only break until the value 5 is replaced in the Rating variable and that is after 7.5.

Here then the first print will be 10 then in every iteration the Rating variable is replaced by 0,1,2... index values respectively, so that 10(default value in Rating variable first), 10(0th index), 9.5 (1st index), 10 (2nd index) such as.

  • Related