python - 脚本不会在 Python3.0 中运行

标签 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()

在 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/

相关文章:

Python mysql 删除行问题

python - 为什么我不能将输出数据帧转换为 csv?属性错误 : 'NoneType' object has no attribute 'to_csv'

python-3.x - python-vlc无法播放并通过youtube视频链接做出响应吗?

python - 更改 python 的默认回溯行为包括项目路径中的更多代码?

python - 使用 isin() 来确定应该打印什么

python - 在表单集中设置 auto_id 并且不要在首次显示时禁用错误

python - 共享列表的多处理

python - 用python解析二进制格式

python - 一次生成100个数字并把它做成一个列表并添加到一个空列表中

python - 在内置函数中赋值