长整型字面量 - 语法无效?

17 投票
2 回答
18983 浏览
提问于 2025-04-18 09:58

我正在使用的一本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

2 个回答

1

你只需要去掉 L 就可以了。

fact = 1

在Python 3.X中,整数的大小是没有限制的,而在Python 2.X中,长整型是有单独的类型的。

31

直接去掉 L 就行了;在 Python 3 中,所有的整数都是长整型。以前在 Python 2 中的 long 现在变成了 Python 3 的标准 int 类型。

原来的代码也不一定要用长整型;Python 2 会根据需要自动切换到 long 类型,反正都是这样。

需要注意的是,Python 2 的支持很快就要结束了(2020年1月1日后不再更新),所以现在你最好换个教程,把时间花在学习 Python 3 上。对于初学者,我推荐 《Think Python, 2nd edition》,这本书已经完全更新为 Python 3,并且可以在网上免费获取。或者你也可以 选择其他 Stack Overflow Python 聊天室推荐的书籍和教程

如果你必须坚持用现在的教程,可以安装一个 Python 2.7 的解释器,这样就可以按照书中的内容学习,而不需要先学习如何把 Python 2 的代码转换成 Python 3 的代码。不过,这样的话你还得学习如何从 Python 2 过渡到 Python 3。

撰写回答