pythonlistwhile-loop

I am a beginner in python, can someone please explain me this piece of code in detail?


marks = [95, 98, 97]

i = 0
while i < len(marks):
    print(marks[i])
    i = i + 1

I want to understand this print(marks[i]) and i = i + 1, what is its use here and why can it not be written before print function?

I am learning about while loop in list data type and I am not able to understand this code.


Solution

  • # create an array with the numbers 95, 98, 97
    # remember that arrays are 0 indexed
    # marks[0] is 95
    # marks[1] is 98
    # marks[2] is 97
    marks = [95, 98, 97]
    
    # set the variable i to 0
    i = 0
    # len(marks) returns the length of the array (3) so while i is less than 3
    # as we are using less i will be 0, 1, 2. When i is 3 it's no longer less then 3 and the loop will end.
    while i < len(marks):
        print(marks[i])
        # add one to i 1 becomes 2 etc (iterate)
        # if you do this before print you would look at marks[1] during first iteration rather than marks[0]
        i = i + 1