Convert Decimal to Binary in Python
Keep dividing by 2, save the remainders, reverse them. bin(10) is 0b1010 if you are in a hurry.
BeginnerBasic Python ProgramsExample 23 of 25
convert-decimal-to-binary.py
Run in browser1# Program to convert decimal to binary without using bin()23num = int(input("Enter a non-negative integer: "))45if num < 0:6 print("Please enter a non-negative integer.")7elif num == 0:8 print("Binary: 0")9else:10 binary_digits = []11 n = num12 while n > 0:13 remainder = n % 214 binary_digits.append(str(remainder))15 n //= 21617 binary_digits.reverse()18 binary_str = ''.join(binary_digits)19 print(f"Binary of {num} is {binary_str}")
Output
Enter a non-negative integer: 10 Binary of 10 is 1010
In this one
- remainders come out backwards — reverse them
- zero needs a special case or you print a blank
What's going on
10 in binary is 1010. You get there by:
10 / 2 → rem 0
5 / 2 → rem 1
2 / 2 → rem 0
1 / 2 → rem 1
Remainders come out backwards (0101), so reverse. bin(10) is '0b1010'. Writing it by hand is the point.
0 is a special case. The while loop never runs, reverse of empty is empty, and you print nothing. That's why num == 0 is handled first.