Zig*_*ggy 7 python int syntax-error python-3.x long-integer
我正在使用的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()
Run Code Online (Sandbox Code Playgroud)
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()
Run Code Online (Sandbox Code Playgroud)
但是在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
Run Code Online (Sandbox Code Playgroud)
Mar*_*ers 21
只是放弃L; Python 3中的所有整数都很长.是什么long在Python 2现在是标准int在Python 3型.
原始代码也不必使用长整数; 无论如何, Python 2会long根据需要透明地切换到该类型.
请注意,所有Python 2支持都将很快结束(在2020/01/01之后不再需要更新),所以此时您可以更好地切换教程并将时间花在学习Python 3上.对于初学者程序员,我建议Think Python,第2版,因为它已经完全针对Python 3进行了更新,并且可以在线免费获得.或者选择任何其他Stack Overflow Python聊天室推荐的书籍和教程
如果你必须坚持当前的教程,你可以改为安装Python 2.7解释器,并且不必学习如何首先将Python 2移植到Python 3代码.但是,您还必须学习如何从Python 2过渡到Python 3.
| 归档时间: |
|
| 查看次数: |
9403 次 |
| 最近记录: |