Using while loop and if statement to tell if a binary has an odd or even number of 1's.

Tim Rowe digitig at gmail.com
Wed Feb 4 20:25:50 EST 2009


2009/2/5 todpose at hotmail.com <todpose at hotmail.com>:
> Using while loop and if statement, I'm trying to get Python to tell me
> whether there are even or odd number of 1's in a binary representation.
> For example, if I give Python a 00000111, then I want it to say that the
> binary representation given has an odd number of 1's.
> If I give it 00010111, then it will tell me that there is an even number of
> 1's.
> I'd appreciate any suggestion.
> Thanks!

Looks like homework to me, so I'll just give a couple of suggestions.

If you're going to prompt the user for the number, you'll get a string
back, and that might be easier to work with than a number. So you need
to set a boolean value for the result, something like:
   even = True
(because so far you've seen zero 1's, and zero is even).

Then you need to loop over each character in the string -- there's
your loop -- and if (there's your if) it's a "1" change the truth
value of even:
    even = !even.

If it is a number rather than a string, you want to do much the same
thing but you'll need the >> and & operators.

Chris has already shown you how this would actually be done in Python,
but that doesn't match your assignment description.


-- 
Tim Rowe



More information about the Python-list mailing list