Why does this not work?

Terry Reedy tjreedy at udel.edu
Tue Jan 7 16:53:53 CET 2003


"Tetsuo" <member16943 at dbforums.com> wrote in message
news:2355358.1041918087 at dbforums.com...
>
> You know you suck if the calculator you are making isn't required to
add
> 2 and 2, and you still can't get it to work.

Others have explained that your conditionals are off due to priority
rules.
But the function also neglects to either return the values (best) or
declare the return values global (dubious since it restricts how you
use the function).  Also, using three conditionals is unnecessarily
cumbersome.  Better:

1. Calculate each return bit separately:

def halfadder(a,b):
  if a not in (0,1) or b not in (0,1):
    raise ValueError, 'inputs must be in (0,1)'
  return a&b, a^b

>>> halfadder(1,1)
(1, 0)
>>> halfadder(1,0)
(0, 1)
>>> halfadder(0,1)
(0, 1)
>>> halfadder(0,0)
(0, 0)


2. Use a dict.

halfadderd={(0,0):(0,0), (0,1):(0,1), (1,0):(0,1), (1,1):(1,0)}

>>> halfadderd[1,1]
(1, 0)
>>> halfadderd[1,0]
(0, 1)
>>> halfadderd[0,1]
(0, 1)
>>> halfadderd[0,0]
(0, 0)

Terry J. Reedy






More information about the Python-list mailing list