2014-06-16 50 views
5

我正在使用的Python教程手冊稍顯過時,但我決定繼續使用它與最新版本的Python一起練習調試。有時候,本書的代碼中有一些東西在更新後的Python中發生了變化,我不確定這是否是其中之一。長整型文字 - 語法無效?

在修復程序以使其可以打印更長的因子值時,它使用long int來解決問題。原來的代碼如下:

#factorial.py 
# Program to compute the factorial of a number 
# Illustrates for loop with an accumulator 

def main(): 
    n = input("Please enter a whole number: ") 
    fact = 1 
    for factor in range(int(n), 0, -1): 
     fact = fact * factor 

    print("The factorial of ", n, " is ", fact) 

main() 

的長整型的版本如下:

#factorial.py 
# Program to compute the factorial of a number 
# Illustrates for loop with an accumulator 

def main(): 
    n = input("Please enter a whole number: ") 
    fact = 1L 
    for factor in range(int(n), 0, -1): 
     fact = fact * factor 

    print("The factorial of ", n, " is ", fact) 

main() 

但運行在Python外殼程序的長整型版本生成以下錯誤:

>>> import factorial2 
Traceback (most recent call last): 
    File "<pyshell#3>", line 1, in <module> 
    import factorial2 
    File "C:\Python34\factorial2.py", line 7 
    fact = 1L 
      ^
SyntaxError: invalid syntax 
+1

(考慮到可能在嘗試並顯示「fact = 1L」的結果時演示了整個問題;其餘代碼僅僅是爲了包袱問題) – user2864740

+0

@ user2864740:但是如果你假定Python 2有一個添加'L'後綴的理由,那麼可能需要剩下的上下文才能確定如何將其用於Python 3?這個假設是錯誤的,但是Python 2的新手無法知道這一點。 –

+0

@MartijnPieters不需要重現問題。問題是提供的代碼導致語法錯誤。這可以用'fact = 1L'複製,如果上面的失敗也會失敗。 – user2864740

回答

15

只需放下L; 全部 Python 3中的整數很長。 Python 2中的long是Python 3中的標準int類型。

原始代碼不必使用長整數; Python 2根據需要透明地切換到long類型無論如何

您可以直接安裝一個Python 2.7解釋器,而無需學習如何先將Python 2移植到Python 3代碼。 Python 2還沒有消失!或者拿起一本不同的書; Think Python, 2nd edition已針對Python 3進行了全面更新並可在線免費獲取,或者可以免費在線獲取,或者pick any of the other Stack Overflow Python chatroom recommended books and tutorials