I have been asked the following:

create inputs for a half-adder using python and the outputs i expect.
I was hoping someone could just have a look at this for me and see if i've got the right idea.

This will work from a copy and paste straight off the bat i should expect.

i1= True
i2= False
o1= ""
o2= ""

if i1 and i2== True:
    o1=True
    o2=True
    print "there is a sum and a carry"

elif i1 or i2== True:
    o1=True
    o2=False
    print "there is a sum but no carry"

elif i1 and i2== False:
    o1=False
    o2=False
    print "the is no sum and no carry"

else:
    raw_input("Input 1 and 2 must be given a value of True or False")

raw_input("")

Recommended Answers

All 4 Replies

No, things don't group the way your code expects. In particular, elif i1 and i2== False: parses as elif (is==True) and (i2==False): . You would need parentheses to change the grouping from the default. But I suggest you go even further. For example your initial test can read simply if i1 and i2: , i.e., no need to compare vs. True and False explicitly since i1 and i2 are already booleans.

No, things don't group the way your code expects. In particular, elif i1 and i2== False: parses as elif (is==True) and (i2==False): . You would need parentheses to change the grouping from the default. But I suggest you go even further. For example your initial test can read simply if i1 and i2: , i.e., no need to compare vs. True and False explicitly since i1 and i2 are already booleans.

Are you saying that instead of that, it should be what is in the commented part?

elif i1 and i2 [B]#== False: <== this bit is not needed?[/B]
    o1=False
   [B] #o1=True?[/B]
    o2=False
    print "There is no sum and no carry"
    [B]#There is a sum that has been carried over and no carry

[/B]

on second look i dont think i understand "parentheses" part .

As a general rule it is best to write these things the long way:
if x == 4 and y == 4:
or:
if x == False and y == False:
In case you don't remember the precendence rules, you can even use:
if (x == False) and (y == False):

if i1==True: is exactly the same as if i1: , just as if i1==False: is identical to if not i1: So if you want to test elif i1 and i2 == False: you should write elif not i1 and not i2: or equivalently but in my mind not as clearly: elif i1==False and i2==False: . As originally written the test is incorrect: elif i1 and i2 == False: , which is true when (1) i1 is True and (2) i2 is False, which is not what you want.

You could also write elif (i1 and i2)==False: or elif not i1 and not i2: , or even elif not (i1 or i2): . Lots of ways to do it right, but not the one in your original post.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.