请忽略这个例子,它只是在我目前正在学习的一本书中。
我在 Netbeans 6.9.1 中运行它,因为 7 不支持 Python :( 我在尝试在输出控制台中运行它时遇到错误。代码与教科书中所写的完全一致。我唯一能想到的是net beans只支持2.7.1,而我正在学习的书是Python 3.1。会不会是这个问题?如果我忽略了什么,请告诉我。
这是基本的脚本;
# Word Problems
# Demonstrates numbers and math
print("If a 2000 pound pregnant hippo gives birth to a 100 pound calf,");
print("but then eats 50 pounds of food, how much does she weigh?");
input("Press the enter key to find out.");
print("2000 - 100 + 50 =", 2000 - 100 + 50);
input("\n\nPress the enter key to exit");
Traceback (most recent call last):
File "/Users/Steve/Desktop/NewPythonProject/src/newpythonproject.py", line 6, in <module>
input("Press the enter key to find out.");
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
-谢谢你们。
最佳答案
问题是 input()
在 Python 3.x 中有不同的含义。在 Python 2.x 中,等效函数是 raw_input()
.
只需将对 input()
的调用替换为对 raw_input()
的调用,它将按预期工作:
# Word Problems
# Demonstrates numbers and math
print("If a 2000 pound pregnant hippo gives birth to a 100 pound calf,")
print("but then eats 50 pounds of food, how much does she weigh?")
raw_input("Press the enter key to find out.")
print("2000 - 100 + 50 =", 2000 - 100 + 50)
raw_input("\n\nPress the enter key to exit")
这导致问题的原因是在 Python 2.x, input()
获取用户文本,然后将其解释为 Python 表达式。当你给它一个空行时,这是一个无效的表达式,它会抛出一个异常。
如果您正在学习 Python 3.x,我强烈建议您使用不同的编辑器。 PyCharm 很棒(虽然不是免费的),Eclipse+Pydev 也在那里。老实说,您并不真的需要 Python 的 IDE - 像 Gedit 这样支持代码高亮显示的优秀文本编辑器是您真正需要的。
另请注意,我删除了分号,这在 Python 中是完全多余的。
关于python - 初学者Python书籍教程问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10400102/