【发布时间】: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