[Tutor] Adding Binary
Ali Raza Ghasemi
ghasema01 at leedslearning.net
Sat Jan 12 21:43:29 CET 2013
I am making a program that adds binary numbers together. The program has to accept two binary values (up to 8 binary digits) and output their total in binary. The output should not contain any leading zeros.
I have a problem in that I don't know how to limit the number digits to 8 as it accepts however many digits you enter, I also want the program to ignore anything other than 8-bit 0s and 1s. It is a python version 3.2.3
Here is my code:
def add_binary_numbers(num1, num2):
while True:
return num1 + num2
if len(str(num1)) > 8:
print("Please enter an 8 bit binary number")
continue
num1 = int(input('please enter the first 8 bit binary number: '),2)
num2 = int(input('please enter the second 8 bit binary number: '),2)
result = add_binary_numbers(num1, num2)
print('the result is', bin(result)[2:])
I know this isn't a question but it is something I needed help on. This program isn't a homework or an assignment. Help would be much appreciated.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130112/f59e36da/attachment.html>
More information about the Tutor
mailing list