[Tutor] Adding Binary
Dave Angel
d at davea.name
Sat Jan 12 23:44:23 CET 2013
On 01/12/2013 03:43 PM, 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.
> 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.
>
>
>
What did you learn from the other thread I told you about? Is Ghadir
Chasemi ghasemmg01 at leedslearning.net related to you? Your email
addresses only differ by a couple of letters.
Your code and his/hers differ only in the ordering and other minor
details, so it'd be an amazing coincidence if it didn't have a common
source.
Why are you still using html/rtf text? Joel Goldstick pointed out that
it frequently messes up formatting on a text mailing list. Look above
and see how all the indentation you presumably had is lost when I see it.
Do you realize that in a function, after an unconditional return
statement, no other code "in" the function will execute. Of course,
without fixing the indentation, nothing is inside the function.
Perhaps you'd find the problem easier if you restate the limit, from 8
digits to a value range. If num1 is less than zero, or greater than
255, it's not correct.
You do know the user could blow up your program by simply entering
something other than a binary value? Like "2' How is that different
than entering a value out of the range you tell him? If you need to
catch the one case, you should catch the other. For that you need
try/catch.
Instead of writing a function that does nothing more complex than a "+"
operator, why not write one that accepts a string from the user, try to
convert it, range check it, catch any exceptions, and loop till a valid
value is encountered.
--
DaveA
More information about the Tutor
mailing list