My binary conversion app only goes up to 5 binary digits, how do I write the code to make it limitless without having to write all the repetitive code

Question:

Is there any way I can make the limitation to the whole number you can convert to binary endless without having to write endless repetitive code for each stage of the whole number to binary conversion.

 #this is my first attempt at creating a integer to binary converter
    #currently only works with 5 digit binary output

    integer = int(input('Please input a whole number you would like converted in to binary '))
    
    remainder_1 = (integer) % 2
    division_1 = (integer) // 2
    #print(remainder_1)
    #print(f"d1 {division_1}")
    
    remainder_2 = (division_1 % 2)
    division_2 = (division_1 // 2)
    if division_2 == 0 and remainder_2 == 0:
        remainder_2 = ('')
    #print(remainder_2)
    #print(f"d2 {division_2}")
    
    remainder_3 = (division_2 % 2)
    division_3 = (division_2 // 2)
    if division_3 == 0 and remainder_3 ==0:
        remainder_3 = ('')
    #print(remainder_3)
    #print(f"d3 {division_3}")
    
    remainder_4 = (division_3 % 2)
    division_4 = (division_3 // 2)
    if division_4 == 0 and remainder_4 ==0:
        remainder_4 = ('')
    #print(remainder_4)
    #print(f"d4 {division_4}")
    
    remainder_5 = (division_4 % 2)
    division_5 = (division_4 // 2)
    if division_5 == 0 and remainder_5 ==0:
        remainder_5 = ('')
    #print(remainder_5)
    #print(f"d5 {division_5}")
    
    remainder_6 = (division_5 % 2)
    division_6 = (division_5 // 2)
    if division_6 == 0 and remainder_6 ==0:
        remainder_6 = ('')
    #print(remainder_6)
    #print(f"d6 {division_6}")
    
    
    
    Binary = (f'{remainder_6}{remainder_5}{remainder_4}{remainder_3}{remainder_2}{remainder_1}')
    print (Binary)

also when printing the binary result is there a way to repeat printing of remainders in order of most significant number to least significant number without having to write it all out as I did above up until remainder 6, Of course depending on how large the whole number input is initially.

Asked By: Mirco Susan

||

Answers:

integer = int(input('Please input a whole number you would like converted in to binary '))
binary = ""

# while integer is greater than zero.
while integer > 0:
    # get the remainder of integer divided by 2.
    remainder = str(integer % 2)
    # concat the remainder as prefix to the binary string
    binary = remainder + binary
    # integer division by 2 on the integer
    integer = integer // 2

print(binary)

Output

Please input a whole number you would like converted in to binary  100
1100100
Answered By: Orbital Bombardment
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.