脚本不能在Python3.0中运行

Blu*_*ift 4 python python-3.x

此脚本将按预期运行并在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()
Run Code Online (Sandbox Code Playgroud)

在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.
Run Code Online (Sandbox Code Playgroud)

我已经尝试运行Python脚本"2to3",但它说不需要进行任何更改.有谁知道为什么脚本不能在Python 3中运行?

Joe*_*ton 13

我猜你需要n //= 10而不是n /= 10.换句话说,您希望明确指定整数除法.否则1 / 10将返回0.1而不是0.请注意,这//=也是有效的python 2.x语法(好吧,从版本~2.3开始,我认为......).

  • @Andrew - `from __future__ import division`只改变默认`/`运算符的作用,```运算符已经存在了很长时间,并且不需要`from __future__ import division`位.`10 // 2` - >`5`甚至可以追溯到python 2.2(这是我现在可以访问的最早的解释器). (5认同)
  • 为了在2.x中使用`// =`语法(并替换`/ =`default),必须包含`from __future__ import division`. (2认同)
  • @Andrew,半右,半错:没有导入,默认保持不变(整数截断之间的`/`,如```),但`// =`仍然可以完美地使用_or_而不导入. (2认同)

Joh*_*hin 5

而现在完全不同的东西:

count = 0
while n:
   n, digit = divmod(n, 10)
   count += ~digit & 1
Run Code Online (Sandbox Code Playgroud)