Python Forum
converting decimal to binary
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
converting decimal to binary
#1
I'm working on an assignment that converts decimal to binary. For each loop it's supposed to print the working number and the remainder (0 for even, 1 for odd), and then print the full binary number at the end.

For the most part I've got it working, but I'm stuck. I've got this print line at the bottom that needs to print once the working number reaches zero. I don't want it to print if the user enters zero. Only if the loop ends in zero. I've tried all kinds of indenting, I've tried switching around the order. I'm just stumped.

Any help is appreciated!

Also, for this assignment I'm not allowed to use list()function, reversed()function, string indexing, for loops or .split()method.

binary = ''
working = int(input('Enter a positive number: '))


while working >= 0:

    if working == 0:
     break

    remainder = working % 2 
    print(working, '', str(remainder) + binary)
    
    if working % 2 == 0:  
        remainder = 0

    else: remainder = 1
    working = working // 2
    binary = str(remainder) + binary

        
print('Your decimal number in binary is ' + binary)
Thank you!
Reply
#2
It sounds like your want to verify that the input is greater than 0. To do that, you can wrap the input in a while loop:

while True:
    working = int(input('Enter a positive number: '))
    if working > 0:
        break

# or

working = 0
while working <= 0:
    working = int(input('Enter a positive number: '))
In addition to that, you have a lot of excess code in there. Lines 7 and 8 can be removed by changing the while loop's condition. Lines 13 through 16 don't actually do anything; the remainder will always be 0 or 1 because of modulus by 2.

binary = ''
working = int(input('Enter a positive number: '))

while working > 0:
    remainder = working % 2
    binary = str(remainder) + binary
    working = working // 2
    print(working, '', binary)

print('Your decimal number in binary is ' + binary)
If you can use the divmod() function, you can shorten this a bit more.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Binary to decimal, print the decimal rs74 3 1,991 Jul-12-2020, 05:25 PM
Last Post: DPaul
  binary to decimal program restingquarterback 3 1,933 Sep-18-2019, 06:24 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020