脚本在Python3.0中无法运行
这个脚本在Python 2.6中会正常运行,并且在测试时不会出现任何错误:
def num_even_digits(n):
"""
>>> num_even_digits(123456)
3
>>> num_even_digits(2468)
4
>>> num_even_digits(1357)
0
>>> num_even_digits(2)
1
>>> num_even_digits(20)
2
"""
count = 0
while n:
digit=n%10
if digit%2==0:
count+=1
n/=10
else:
n/=10
return count
if __name__ == '__main__':
import doctest
doctest.testmod()
在Python 3.0中,输出是这样的:
**********************************************************************
File "/home/calder/My Documents/Programming/Python Scripts/ch06.py", line 3, in
__main__.num_even_digits`
Failed example:
num_even_digits(123456)
Expected:
3
Got:
1
**********************************************************************
File "/home/calder/My Documents/Programming/Python Scripts/ch06.py", line 5, in
__main__.num_even_digits
Failed example:
num_even_digits(2468)
Expected:
4
Got:
1
**********************************************************************
1 items had failures:
2 of 5 in __main__.num_even_digits
***Test Failed*** 2 failures.
我尝试运行了Python脚本“2to3”,但它说不需要任何更改。有没有人知道为什么这个脚本在Python 3中不能运行?
3 个回答
3
我觉得这个问题可能是因为在Python 2.x中,"/="这个运算符返回的是整数结果,而在Python 3.x中,它返回的是浮点数。你可以试着把"/="改成"//="。这样在Python 3.x中,"//="会像在Python 2.x中的"/="一样返回整数结果。
5
接下来我们要聊点完全不同的内容:
count = 0
while n:
n, digit = divmod(n, 10)
count += ~digit & 1
13
我猜你需要用 n //= 10
而不是 n /= 10
。换句话说,你想要明确进行整数除法。否则,像 1 / 10
这样的计算会返回 0.1
,而不是 0
。另外,//=
这个写法在 Python 2.x 版本中也是有效的(我想大约从 2.3 版本开始就可以用了...)。