Im honestly going to die in this class! We have a project that we need to do on adding binary numbers and I cannot manage to get past the first step...checking the users strings for 1's and 0's. If it contains anything else...the code is supposed to reject the users input, but I cant figure out exactly what im doing wrong here! Can anyone help me?

binStr = raw_input('Please input a binary number:')
if '1' and '0' in binStr:
    print "Good"
else:
    print "must contain only 1's and 0's!"

After this, we are supposed to write code that can add the binary numbers. Any guidance you guys have and examples on this, I would very much appreciate. I have never programmed before, this is my first time taking a programming course, I dont want to skip out on this project becuase I cant figure it out. Please help me :)

Like this:

binStr = raw_input('Please input a binary number:')
if all(c in '10' for c in binStr):
    print "Good"
else:
    print "must contain only 1's and 0's!"

or like this:

try:
    bin_num = int(raw_input('Please input a binary number:'),2)
except:
    print "must contain only 1's and 0's!"
else:
    print "Good number. Value",bin_num

Thank you! I was going about it the right way but I knew something was missing. Do you have any tips or hints on how to get python to add binary numbers through string manipulation only? Meaning, we are not allowed to use built in functions to convert to binary, we have to make equations to do it and use strings..

Add carry bit handling for multiple bits to this:

def bitadd(a,b):
    " return carry bit and sum for single bit '01' addition "
    return (str(int(a == b == '1')), int(a =='1' or b=='1'))

print [(a,b,bitadd(a,b)) for a in ('0','1') for b in ('0','1')]
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.