[Tutor] Adding Binary

Alan Gauld alan.gauld at btinternet.com
Sat Jan 12 23:48:50 CET 2013


On 12/01/13 20:43, Ali Raza Ghasemi wrote:
> 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.

The first thing to realize is that all numbers in a computer are binary. 
Its the repressentation of them on screen that determines whether they 
are in decimal, hex or binary format. Display is a string function. 
Addition is a numeric function so you are going to have to translate 
between the two. And its probably best if your program separates the two 
concepts.

> 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

This is presumably an exercise somewhere since we had an identical 
request earlier.
And I ask the same question, why would you want to restrict the length, 
its a bizarre requirement. But since I assume its part of the problem 
spec I'll ignore that...


> to ignore anything other than 8-bit 0s and 1s.

OK, that's an extra wrinkle we didn't have last time but its a valid
thing to check.

> Here is my code:

And here is a problem, you seem to have posted in HTML and thats lost 
all the formatting so we don't know how your code looks. Pleae post in 
plain text to the list. Especially because formatting is critical in 
Python... But your first post format is visible ok so I'll use that for 
reference...

> 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

Because the return ends the function the lines after that are *never* 
executed. You probably want the return at the end of the function after 
doing all the checks.

And you probably don't want the checks inside the function, its better 
to keep a function that adds to just doing addition.

Lets assume you do swap them round the next problem is that str() will 
convert to decimal not binary. So you really want to use bin() there.
And bin will add a '0b' prefix so your len() needs to check for 10 not 8 
characters.

Finally calling continue repeats the loop but since you don't change 
anything - nowhere to enter a new number it just repeats forever.
So a bit of a rethink of the logic needed there.

> num1 = int(input('please enter the first 8 bit binary number: '),2)
> num2 = int(input('please enter the second 8 bit binary number: '),2)

This is fine except by converting the numbers straight away you miss anb 
opportunity to check the user input. And its always best to validate 
input as soon as possible. So i suggest just read the string and check 
the length there and then. Then after checking convert to int()

That way you don't need the check inside the function.

Finally the int(n,2) won't convert if there are non 1/0 characters in 
the string so you can simply catch an error in int() to ensure you get 
valid 1s and 0s.

 >>> int('1213',2)
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 2: '1213'

HTH

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list