简体   繁体   English

脚本不能在Python3.0中运行

[英]Script won't run in Python3.0

This script will run as expected and pass doctests without any errors in Python 2.6: 此脚本将按预期运行并在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()

In Python3.0 this is the output: 在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.

I have tried running the Python script "2to3", but no changes are needed it says. 我已经尝试运行Python脚本“2to3”,但它说不需要进行任何更改。 Does anyone know why the script will not run in Python 3? 有谁知道为什么脚本不能在Python 3中运行?

I'm guessing you need n //= 10 instead of n /= 10 . 我猜你需要n //= 10而不是n /= 10 In other words, you want to explictly specify integer division. 换句话说,您希望明确指定整数除法。 Otherwise 1 / 10 will return 0.1 instead of 0 . 否则1 / 10将返回0.1而不是0 Note that //= is valid python 2.x syntax, as well (well, starting with version ~2.3, I think...). 请注意//=是有效的python 2.x语法(好吧,从版本~2.3开始,我认为......)。

And now for something completely different: 而现在完全不同的东西:

count = 0
while n:
   n, digit = divmod(n, 10)
   count += ~digit & 1

I think this could be because operator "/=" in Python 2.x returned integer result while in Python 3.x it returns float. 我认为这可能是因为Python 2.x中的运算符“/ =”返回整数结果,而在Python 3.x中它返回float。 Try to change "/=" to "//=". 尝试将“/ =”更改为“// =”。 "//=" return integer result in Python 3.x in the same way as "/=" in Python 2.x. “// =”以与Python 2.x中“/ =”相同的方式在Python 3.x中返回整数结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM