Book a free demo

Easy ยท ages 11+ ยท while loop ยท remainder ยท strings

Decimal to binary in Python.

Turn a number into binary by repeatedly dividing by 2.

The program

Press Run to see what it prints. Change anything you like, then run it again.

def to_binary(n):
    if n == 0:
        return "0"
    bits = ""
    while n > 0:
        bits = str(n % 2) + bits
        n = n // 2
    return bits

for number in [5, 10, 25, 100, 255]:
    print(number, "is", to_binary(number), "in binary")
print("Check:", bin(25), int("11001", 2))
5 is 101 in binary
10 is 1010 in binary
25 is 11001 in binary
100 is 1100100 in binary
255 is 11111111 in binary
Check: 0b11001 25

How it works

  1. Binary uses only 0 and 1. Each place is worth twice the one to its right: 1, 2, 4, 8, 16, ...
  2. To convert, keep dividing by 2. The remainders, read from the last to the first, are the binary digits.
  3. Python can do it for you with bin(), and int("11001", 2) turns binary back to a number.
See the Python path โ†’

Try this

  • Convert your age.
  • Write to_decimal to go the other way.
  • How many bits does 1000 need?

Stuck on an error? Read how to debug Python.

Similar ideas

More programs

All programs โ†’

FAQ

Decimal to binary: questions

What does the decimal to binary program do?

Turn a number into binary by repeatedly dividing by 2. It prints: 5 is 101 in binary / 10 is 1010 in binary / 25 is 11001 in binary โ€ฆ

Which Python ideas does it use?

while loop, remainder, strings. Easy level, suitable from about age 11.

How do I run it?

Press Run on this page. To run it on your own computer, install Python 3 and save the code in a file ending in .py. It prints the same thing.

What should I try next?

Convert your age. Write to_decimal to go the other way. How many bits does 1000 need?

Start a conversation

Want a teacher to guide the learning?

Tell us the learner's age and what they can already do, and we will suggest a starting point. A parent or guardian can make the enquiry.

  • Tell us the learnerโ€™s age or grade and goals
  • Weโ€™ll suggest a suitable class or learning path
  • Weโ€™ll confirm format, timing and fees with a parent or guardian

For a childโ€™s class, please have a parent or guardian send the enquiry. Avoid sharing passwords or sensitive personal details.

Weโ€™ll use your details only to respond to this request.

Play it, don't just read it

Write some code right now

Free games that need no sign-up. Pick one and play for five minutes.

All free games โ†’
Chat on WhatsApp
Esc

Try