To print first n even numbers in reverse order using while loop | Sololearn: Learn to code for FREE!

+1

To print first n even numbers in reverse order using while loop

#4 print first n even numbers in reverse order n= int(input()) num= 0 x= 0 listt= [] while n>x: if num%2==0: listt.append(str(num)) x+=1 num+=1 listt= listt.reverse() #for loop is working fine but using while loop it is creating a problem #sample input- 5 #desired output- 8,6,4,2,0

1/24/2022 4:31:06 AM

Shaurya Agarwal

11 Answers

New Answer

+4

n= int(input()) num= 2 #debug listt= [] while n>0: listt.append(num) n-=1 num+=2 listt.reverse() print(listt)

+4

This just indicates that the `reverse` method does not return anything. It only modifies the existing list. It does not return an updated list. Don't bother doing listt = listt.reverse(). If you just want to reverse a list, do listt.reverse() to modify your listt. listt.reverse() print(listt)

+3

Now solve this problem without the extra variable num ☺️

+3

Thanks to all for your help πŸ™πŸ™

+3

Brian, great example with bitwise operation πŸ‘, but it's easy ☺️. Try all the same to print the n-th number of even numbers. Example: input 5 output 10,8,6,4,2

+2

Shaurya Agarwal the description says to print them in reverse order, but the #desired output shows them in forward order. Which is correct?

+2

n = int(input()) # If n is odd, force n to next lower even. if n&1: n -= 1 #now only even numbers will print while n>0: print(n, end=',') n -= 2 print(n) #final 0 without comma

+2

Solo oops, I missed that detail. Okay, it is easily corrected with the same loop, only a different adjustment to n. #print the first n even Natural numbers in reverse order n = int(input()) n = 2*(n - 1) while n>0: print(n, end=',') n -= 2 print(n) #final 0 without comma

+2

Solo thanks bro! I know there is debate about whether 0 is even, so I included it only because the OP did. There is also debate about whether 0 belongs in the Natural number set. I decided to adopt it in that set in my comment because it is the only difference that would distinguish Natural numbers from Counting numbers. On the other hand, 0 is most unnatural!

+1

Brian corrected

+1

Brian, yes, you did it. πŸ‘πŸ‘πŸ‘ Except 0 is not an even number ☺️.