Reputation: 85
I have written the following block:
number = 12
def checkio(number):
count = 0
for n in bin(number):
print n
if n == 1:
count += 1
print count
checkio(number)
The output I get is:
0
0
b
0
1
0
1
0
0
0
0
0
I can't understand why I'm able to iterate through n
in the binary number and print
it, but my if
won't work correctly and won't add to my count
variable.
Why does this happen?
Upvotes: 1
Views: 45
Reputation: 122150
When you iterate through the string produced by bin
, each character is itself a one-character string. So the reason this doesn't work is, simply:
1 != '1'
You will need to convert the characters back into integers to compare (be aware that int('b')
won't work!), or compare to a string:
if n == '1':
Upvotes: 2