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
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:
a>4
) inside the loop; the loop condition has been substituted by True
.break
instruction causes the exit of the loop.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.