Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Basics Functions and Looping Raising Exceptions

walter fernandez
walter fernandez
4,992 Points

hello, I want to write a program that subtracts binary numbers.

I want to subtract two binary numbers without using the binary function and without convert binary numbers to decimal numbers. Thanks.

3 Answers

Steven Parker
Steven Parker
231,248 Points

:mailbox_with_mail: Hi, I got your request. But numbers are always stored inside the computer in binary. The conversion to and from decimal is part of the input and output operations.

So I suspect what you really want it to input numbers in binary, and then display the result in binary also. This is not too hard, because the "int" function that you would use to convert input into a number can be told what number base to use. And when formatting for output, you can also specify a binary conversion. So for example:

one = int(input("Enter the first binary number: "), 2)  # the "2" here means "in binary"
two = int(input("Enter the other binary number: "), 2)
result = one - two                                      # the actual math is nothing special
print(f"The binary difference is {result:b}.")
walter fernandez
walter fernandez
4,992 Points

hello, sorry I did not that I can mark any answer as the Best answer. just the answer does not appear in base two. I am trying to add --- ,2 --- inside the print to see if the result become in base two, I am trying to figure out.

Steven Parker
Steven Parker
231,248 Points

Only "input" takes a second argument for base.
For the "print", it's the ":b" in the formatting token that causes the output to be binary.