此脚本将按预期运行并在 Python 2.6 中通过 doctests 而不会出现任何错误:
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()
在 Python3.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 中运行?
最佳答案
我猜你需要 n//= 10
而不是 n/= 10
。换句话说,您想明确指定整数除法。否则 1/10
将返回 0.1
而不是 0
。请注意,//=
也是有效的 python 2.x 语法(好吧,我认为从版本 ~2.3 开始......)。
关于python - 脚本不会在 Python3.0 中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3543453/