Python for Absolute Beginners:第2章#Word问题

时间:2017-01-12 12:39:53

标签: python traceback

我开始研究着名的Absolute Beginners 3e Python。我一直在忠实地复制代码,但有些人如何不断收到错误消息。所以,我使用了help / examples文件夹中提供的代码,但仍然得到相同的消息:

Traceback (most recent call last):
  File "word_problems.py", line 6, in <module>
    input("Press the enter key to find out.")
  File "<string>", line 0

    ^
SyntaxError: unexpected EOF while parsing

有人可以给我一个线索,或解释什么不起作用。我也可以发布部分代码,其余部分相同(但我想很多人都知道这本书),但有不同的问题:

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)

3 个答案:

答案 0 :(得分:1)

使用raw_input代替input

  

如果您使用input,则您键入的数据将被解释为a   Python表达式意味着你最终得到了gawd知道   目标变量中的对象类型,以及广泛的对象   可生成的异常范围。所以你不应该使用input   除非您正在进行临时测试,否则将被使用   只有那些对Python表达有所了解的人。

     

raw_input总是会返回一个字符串,因为,那就是你   总是键入...但随后您可以轻松地将其转换为特定的   您想要的类型,并捕获可能发生的特定异常。   希望通过这种解释,知道你是哪一个是明智的   应该使用。

source 1 | source 2

答案 1 :(得分:0)

您使用的是python2版本

所以你是raw_input()而不是input()

你的代码应该是:

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)

如果您只想在空白输入或输入时显示输出,您可以将简单验证放在:

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?")
ur = raw_input("Press the enter key to find out.")

if ur== '':
    print "She weigh ", 2000 - 100 + 50,"pounds"
else:
    print 'SOrry!'

答案 2 :(得分:0)

正如其他人所说的那样,因为python 3中的input在python 2中表现得像raw_input。因此,一个解决方案就是使用raw_input来实现在python 2中工作。

但是,如果你按照这本看起来像是使用python 3的书,我认为你现在切换到python 3会好得多,你不应该遇到这些问题在书中更进一步。