【问题标题】:Long Int literal - Invalid Syntax?Long Int 文字 - 无效的语法?
【发布时间】:2014-08-06 14:55:55
【问题描述】:

我正在使用的 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()

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 = 1L
    for factor in range(int(n), 0, -1):
        fact = fact * factor

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

main()

但是在 Python shell 中运行 long int 版本的程序会产生以下错误:

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

【问题讨论】:

  • (考虑到在尝试并显示fact = 1L 的结果时可能已经证明了整个问题;为了这个问题,其余代码只是包袱)
  • @user2864740:但如果您假设 Python 2 有理由添加 L 后缀,那么可能需要上下文的其余部分来确定如何将其使用转换为 Python 3?这个假设是错误的,但是 Python 2 的新手无法知道这一点。
  • @MartijnPieters 不需要重现问题。问题是提供的代码导致语法错误。这可以用fact = 1L 复制,如果上述失败也会失败。
  • @user2864740:是的,我知道。这不是我要说的重点。如果 OP 正在尝试将代码转换为 Python 3,那么 他们应该使用什么来代替 fact = 1L?为此,很可能是上下文很重要。

标签: python python-3.x int syntax-error long-integer


【解决方案1】:

只需删除L; Python 3 中的 all 整数都是长整数。 Python 2 中的 long 现在是 Python 3 中的标准 int 类型。

原始代码也不必使用长整数; Python 2 会根据需要透明地切换到 long 类型无论如何

请注意,所有 Python 2 支持即将结束(2020/01/01 之后不再更新),因此此时您最好切换教程并花时间学习 Python 3。对于初学者程序员我推荐Think Python, 2nd edition,因为它已针对 Python 3 进行了全面更新,并且可以在线免费获得。或pick any of the other Stack Overflow Python chatroom recommended books and tutorials

如果您必须坚持当前的教程,您可以安装 Python 2.7 解释器,然后按照自己的方式阅读本书,而无需先学习如何将 Python 2 移植到 Python 3 代码。但是,您还必须学习如何从 Python 2 过渡到 Python 3。

【讨论】:

    【解决方案2】:

    你只需要删除L

    fact = 1
    

    Python 3.X 整数支持无限大小,而 Python 2.X 具有单独的长整数类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多