How to print (all) the result(s) of a while loop in reverse order?

Question:

#decimalToBinary

num=int(input("Enter number"))

while num!=0:
    bin=num%2
    num=num//2
    print(bin,end=" ")

Let’s say the input,here, is 13. It’ll give the output:1 0 1 1.
How can I print it in reverse (i.e, 1 1 0 1) ?

Asked By: The_L0s3r.

||

Answers:

Store it in a list, then print it in reverse.


#decimalToBinary

num=int(input("Enter number"))
output = []
while num!=0:
    bin=num%2
    num=num//2
    output.append(bin)

print (output[::-1])

To print the results as a string

print (' '.join([str(o) for o in output[::-1]]))

EDIT
As suggested in comments, Here is the approach avoiding lists.

#decimalToBinary

num=int(input("Enter number"))
output = ''
while num!=0:
    bin=num%2
    num=num//2
    output = str(bin) + output

print (output)

for your example this should work:

num=int(input("Enter number"))
lst=list()
while num!=0:
    bin=num%2
    num=num//2
    lst.append(bin)

print(lst,lst[::-1])

output:

Enter number13
[1, 0, 1, 1] [1, 1, 0, 1]
Answered By: Mig B

Without resorting to some more difficult tricks trying to manipulate where you print things in a console, it might be easier to build up a string in the loop:

num=int(input("Enter number"))
digits = []
while num!=0:
    bin=num%2
    num=num//2
    digits.append(bin)

and reverse it afterwards:

print(digits[::-1]) #this will possibly need formatting.

To format this with spaces try:

print(" ".join(str(x) for x in L[::-1]))
Answered By: doctorlove

You can build the whole result in a string, then reverse it :

num = 13
bin = ""
while num!=0:
    bin += str(num%2) + " "
    num=num//2

bin = bin.strip();

print(bin[::-1])

Outputs :

1 1 0 1

Answered By: Cid

Well, you could append the values of bin in an array or just make bin an array and append to it and then print the array in reverse.

from __future__ import print_function
num=int(input("Enter number"))
bin = []
while num!=0: 
    bin.append(num%2) 
    num=num//2
print(*bin[::-1], sep=' ')
Answered By: Abhijeeth S
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.