我使用的 Python 教程书有点过时,但我决定继续使用最新版本的 Python 来练习调试.有时我学到的书中代码中的一些东西在更新的 Python 中发生了变化,我不确定这是否是其中之一.
The Python tutorial book I'm using is slightly outdated, but I've decided to continue using it with the latest version of Python to practice debugging. Sometimes there are a few things in the book's code that I learn have changed in the updated Python, and I'm not sure if this is one of them.
在修复程序以便它可以打印更长的阶乘值时,它使用 long int 来解决问题.原代码如下:
While fixing a program so that it can print longer factorial values, it uses a long int to solve the problem. The original code is as follows:
#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 版本如下:
The long int version is as follows:
#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 版本的程序会产生以下错误:
But running the long int version of the program in the Python shell generates the following error:
>>> import factorial2
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
import factorial2
File "C:Python34factorial2.py", line 7
fact = 1L
^
SyntaxError: invalid syntax
只要把L
;Python 3 中的 all 整数都是长整数.Python 2 中的 long
现在是 Python 3 中的标准 int
类型.
Just drop the L
; all integers in Python 3 are long. What was long
in Python 2 is now the standard int
type in Python 3.
原始代码也不必使用长整数;Python 2 根据需要透明地切换到 long
类型反正.
The original code doesn't have to use a long integer either; Python 2 switches to the long
type transparently as needed anyway.
请注意,所有 Python 2 支持即将结束(2020/01/01 之后不再更新),因此此时您最好切换教程并花时间学习 Python 3.对于初学者我推荐 Think Python,第 2 版,因为它已针对 Python 3 进行了全面更新且免费可在线获取.或者选择任何其他 Stack Overflow Python 聊天室推荐的书籍和教程
Note that all Python 2 support is shortly ending (no more updates after 2020/01/01), so at this point in time you'd be much better of switching tutorials and invest your time in learning Python 3. For beginner programmers I recommend Think Python, 2nd edition as it is fully updated for Python 3 and freely available online. Or pick any of the other Stack Overflow Python chatroom recommended books and tutorials
如果您必须坚持当前的教程,您可以安装 Python 2.7 解释器,然后按照自己的方式阅读本书,而无需先学习如何将 Python 2 移植到 Python 3 代码.但是,您还必须学习如何从 Python 2 过渡到 Python 3.
If you must stick to your current tutorial, you could install a Python 2.7 interpreter instead, and work your way through the book without having to learn how to port Python 2 to Python 3 code first. However, you'd then also have to learn how transition from Python 2 to Python 3 in addition.
这篇关于Long Int 文字 - 无效的语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!