簡體   English   中英

腳本不能在Python3.0中運行

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

此腳本將按預期運行並在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開始,我認為......)。

而現在完全不同的東西:

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

我認為這可能是因為Python 2.x中的運算符“/ =”返回整數結果,而在Python 3.x中它返回float。 嘗試將“/ =”更改為“// =”。 “// =”以與Python 2.x中“/ =”相同的方式在Python 3.x中返回整數結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM