Click here to Skip to main content
15,889,281 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hey all,

I'm a student and doing a practice for my exam. I will have to create a program that converts an input into binary.

So far, I got the code working BUT I need my output to be in reverse order.

I used
Python
[::-1]
yet it doesn't seem to be doing it.

Thanks!

What I have tried:

Python
def binary_converter (num):
    while num != 0:
        output = num % 2 #0 or 1
        num = num // 2
        reverse = str(output) #change into string
        print (reverse[::-1], end="") #reverse not working

print ("Enter a number:")
num = int(input())
binary_converter(num)
Posted
Updated 10-May-18 22:18pm
v2

1 solution

output is always just a one-letter string (because it's inside the loop), so reversing it just gives the same string.

What you need to do, is reversing the whole string before printing it:
Python
def binary_converter(num):
    reverse = ""
    while num != 0:
        output = num % 2 # 0 or 1
        num = num // 2
        reverse += str(output)
    print (reverse[::-1], end="")
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900