pythonwhile-loop

Unable to use Python While Loop as I want


I am new to Python and trying to learn While loop.

list1 = [1,2,3,4,5,6,7]

a = max(list1)
idx = len(list1)-1

while a>4:
    a = list1[idx]
    print(a)
    idx = idx-1

As i am using 'while a>4', I was expecting the output to be only [7,6,5] but i get output as [7,6,5,4].

What am i not getting right?

Thank you


Solution

  • A possible solution:

    list1 = [1,2,3,4,5,6,7]
    
    # the initialization of a is not necessary
    #a = max(list1)
    idx = len(list1)-1
    
    while True:
        a = list1[idx]
        if a>4:
            print(a)
        else:
            break
        idx = idx-1
    

    My code is very similar to your from your code:

    1. I have moved the exit condition (a>4) inside the loop; the loop condition has been substituted by True.
    2. The break instruction causes the exit of the loop.
    3. The execution of the print instruction is controlled by the if so no number greater than 4 will be printed.

    The output of the execution is:

    7
    6
    5
    

    as you wish.