【问题标题】:Python for Absolute Beginners: Chapter 2 #Word Problems [duplicate]面向绝对初学者的 Python:第 2 章 #Word 问题 [重复]
【发布时间】:2017-01-12 12:39:53
【问题描述】:

我已经开始为 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)

【问题讨论】:

  • 那是因为您使用的是python 2。试试raw_input()
  • 重点是,你应该升级你的Python版本;毫无疑问,您以后会遇到其他不一致的地方。
  • 更新到哪一个?我使用的是 Python 2.7,我有几门课程建议使用该版本,因为他们使用的是旧程序。

标签: python traceback


【解决方案1】:

使用raw_input 而不是input

如果您使用input,那么您键入的数据将被解释为 Python 表达式,这意味着你最终会得到 gawd 知道 目标变量中有什么类型的对象,以及很宽的 可以生成的异常范围。所以你不应该使用input 除非您将某些东西放入临时测试中,否则将被使用 只有对 Python 表达式有一点了解的人。

raw_input 总是返回一个字符串,因为,哎呀,这就是你 总是输入...但是您可以轻松地将其转换为特定的 键入您想要的,并捕获可能发生的特定异常。 希望有了这个解释,很容易知道你是哪个 应该使用。

source 1 | source 2

【讨论】:

  • 谢谢,我没想到!几年前我上了一门 Python 课程,但忘记了那个细节,我只是假设原始代码是正确的。谢谢。
【解决方案2】:

正如其他人所说,这是因为 input 在 python 3 中的行为类似于 raw_input 在 python 2 中的行为。所以一种解决方案是使用 raw_input 让它在 python 2 中工作。

但是,如果您正在阅读这本书,似乎它使用的是 python 3,我认为您现在最好切换到 python 3,并且您不应该在本书中进一步遇到这些问题。

【讨论】:

    【解决方案3】:

    你使用的是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!'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-30
      • 2015-03-08
      相关资源
      最近更新 更多