+ 2

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

24th Jan 2022, 4:31 AM
Shaurya Agarwal
Shaurya Agarwal - avatar
11 Respostas
+ 5
n= int(input()) num= 2 #debug listt= [] while n>0: listt.append(num) n-=1 num+=2 listt.reverse() print(listt)
24th Jan 2022, 5:39 AM
Solo
Solo - avatar
+ 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)
24th Jan 2022, 4:57 AM
Simba
Simba - avatar
+ 3
Now solve this problem without the extra variable num â˜ș
24th Jan 2022, 6:50 AM
Solo
Solo - avatar
+ 3
Thanks to all for your help 🙏🙏
25th Jan 2022, 7:36 AM
Shaurya Agarwal
Shaurya Agarwal - avatar
+ 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
25th Jan 2022, 3:24 PM
Solo
Solo - avatar
+ 2
Shaurya Agarwal the description says to print them in reverse order, but the #desired output shows them in forward order. Which is correct?
24th Jan 2022, 8:35 AM
Brian
Brian - avatar
+ 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
25th Jan 2022, 10:01 AM
Brian
Brian - avatar
+ 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
25th Jan 2022, 7:25 PM
Brian
Brian - avatar
+ 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!
25th Jan 2022, 10:50 PM
Brian
Brian - avatar
+ 1
Brian corrected
25th Jan 2022, 7:30 AM
Shaurya Agarwal
Shaurya Agarwal - avatar
+ 1
Brian, yes, you did it. 👏👏👏 Except 0 is not an even number â˜ș.
25th Jan 2022, 9:08 PM
Solo
Solo - avatar