The following Python script takes an integer entered by user and convert it to binary. Explaination also included 🤙😀.
#this Python script converts integer to binary
while True:
try:
inputDecimal = int(input("Enter the number to convert to binary..."))
# take care of the int 0 as the algorithm
#iteration stop at 1
if inputDecimal == 0:
print('0b0')
quit( )
#check if inputDecimal is +ve or -ve
#temporary remove -ve sign
if inputDecimal < 0:
sign = '-'
wholeNum = inputDecimal * (-1)
else:
sign = ''
wholeNum = inputDecimal
break
except ValueError : #check that inputDecimal is a integer
print("Please enter an integer")
#conversion starts...
binaryListReverse = [ ]
#algorithm for getting the 1s and 0s
while wholeNum >= 1:
remainder = wholeNum%2
wholeNum = wholeNum//2
binaryListReverse.append(remainder)
#Reverse List
listLength = len(binaryListReverse)
binaryList = [ ]
for element in range(listLength-1, -1, -1):
binaryList.append(binaryListReverse[element])
binaryInStr =sign+'0b' + ''.join(str(x) for x in binaryList)
#print(binaryListReverse)
#print( binaryList)
print(binaryInStr)
When program is executed:


Code explaination:
While loop (line 2 to 24) : the while loop check the variable that the user entered. If user entered integer 0, the binary equivalent will be printed and the program will end using the ‘quit’ method. This is necessary because the algorithm iteration stop at integer 1.
Line 14 to 19: If the user entered a -ve number, the sign variable will initialize as ‘-‘ (-ve sign). We will use sign variable later when we perform concatenation at the end. The -ve sign is also remove as the algo is the same for +ve and -ve integers. Variable wholeNum is initialized to inputDecimal. The break method will exit the while loop and continue with the remaining code.
The try/exception takes care of non integer input. When input is non integer, exception with ValueError will be raised which return True. Hence the while loop will repeat until the user has input an integer.
Line 28 to 34: The algorithm starts. The binaryListReverse is use to store the remainder from the modulo operation. It is named with the word ‘Reverse’ because the 1s and 0s in the list is arrange from left to right whereas binary are arrange from right to left.
The integer will be divided by 2 and the remainder( either 1 or 0 ) will be stored in the list. After division, the whole number will be stored in wholeNum variable. And the process repeats until wholeNum is < 1.
Line 37 to 48: Get the length of binaryListReverse and iterate through the list, starting from the last element and store the elements into binaryList list. In this way, the 1s and 0s are arrange as per binary logic.
Next convert binarytList to string(to remove the commas), and concatenate with ‘0b'(which stands for binary system) and variable ‘sign’ (from line 15 and 18). And store them in binaryInStr.
Lastly, print binaryInStr. ☕🥟