Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 迭代计算不正确_Python_Python 2.7_If Statement_Binary - Fatal编程技术网

Python 迭代计算不正确

Python 迭代计算不正确,python,python-2.7,if-statement,binary,Python,Python 2.7,If Statement,Binary,我已经写了下面的代码块: number = 12 def checkio(number): count = 0 for n in bin(number): print n if n == 1: count += 1 print count checkio(number) 我得到的结果是: 0 0 b 0 1 0 1 0 0 0 0 0 我不明白为什么我能够在二进制数中迭代n并打印它,但是我的if不能正

我已经写了下面的代码块:

number = 12

def checkio(number):
    count = 0
    for n in bin(number):
         print n
         if n == 1:
             count += 1
    print count


checkio(number)
我得到的结果是:

0
0
b
0
1
0
1
0
0
0
0
0
我不明白为什么我能够在二进制数中迭代
n
并打印它,但是我的
if
不能正常工作,也不能添加到我的
计数
变量中


为什么会发生这种情况?

当您遍历由
bin
生成的字符串时,每个字符本身就是一个字符串。所以这不起作用的原因很简单:

1 != '1'
您需要将字符转换回整数进行比较(请注意,
int('b')
不起作用!),或者与字符串进行比较:

if n == '1':
检查应为“如果n=='1'”