Python Program to Convert Decimal to Binary
hardwhile loopPython
Repeated division by 2 gives a number's binary digits — read from the last remainder to the first.
The question
Read a positive integer and print its binary form. Use repeated division by 2 — do not use bin().
The code
program.py
n = int(input())
bits = ""
while n > 0:
bits = str(n % 2) + bits
n //= 2
print("Binary =", bits)Input
185
Output
Binary = 10111001
How it works
- 1n % 2 is the next binary digit, starting from the right.
- 2Put each new digit in front: bits = str(n % 2) + bits.
- 3n //= 2 moves to the next digit; stop when n is 0.
Common mistakes
- Adding the digit at the end (bits + str(...)), which prints the binary number backwards.
- Using bin(n) when the question says not to — it also adds a 0b prefix.
Now solve a similar question yourself
A new Python question every time, checked instantly.
