【问题标题】:Raw_input() Python (Learn Python the Hard Way Exercise 11) [closed]Raw_input() Python(艰难地学习 Python 练习 11)[关闭]
【发布时间】:2017-10-18 21:24:34
【问题描述】:

我正在做 Zed Shaw 的“Learn Python the Hard Way”第 3 版中的提问练习,我的代码如下所示:

print "How old are you?",

age = raw_input()

print "How tall are you?",

height = raw_input()

print "How much do you weigh?",

weight = raw_input()

print "So, you're %r old, %r tall and %r heavy." % (age, height, weight)

输出应该是这样的:

How old are you? 38

How tall are you? 6'2"

How much do you weigh? 180lbs

So, you're '38' old, '6\'2"' tall and '180lbs' heavy.

但是,因为我使用的是 Python 3,所以输出最初看起来像:

How old are you?
Traceback (most recent call last):
  File "script.py", line 2, in <module>
    age = raw_input()
NameError: name 'raw_input' is not defined

然后就像我用 input() 替换 raw_input() 一样:

How old are you?
Traceback (most recent call last):
  File "script.py", line 2, in <module>
    age = input()
EOFError: EOF when reading a line

【问题讨论】:

  • 看起来像 Python 3 系统上的 Python 2 代码。另一方面,print "How old are you?", 似乎可以工作,这就是 Python 2 的语法。这里有点可疑。
  • print 应该是 print()。这是 Py2 和 Py3 之间的另一个区别
  • 可能与此有关? stackoverflow.com/q/17675925/10077

标签: python input raw-input


【解决方案1】:

看起来您拥有的代码是 python 2 代码。这是使用 python 3 语法的修订版。

Here 是关于最后一行.format() 调用的一些读物。我认为 .format 方法更容易理解。

here 是python 3 中input() 函数的一些读物

age = input("How old are you?")

height = input("How tall are you?")

weight = input("How much do you weigh?")

print("So, you're {} old, {} tall and {} heavy.".format(age, height, weight))

【讨论】:

  • 我做了一个: print("你多大了?",) age = input("你多大了?") 得到:你多大了?你几岁? Traceback(最近一次调用最后一次):文件“script.py”,第 2 行,在 中 age = input("你多大了?") EOFError: EOF when reading a line
  • 你能确认你使用的是什么版本的python吗?此外,您不必在输入之前print("How old are you?")。输入将自动打印“你几岁?”在获取用户输入之前到终端。
  • 你好,不管他用的是哪个版本的python,你做的代码都适用于python2.xx和python3.xx
  • 不完全正确。如果你在 python3 中使用print "something",它会给你一个SyntaxError: invalid syntax。您必须使用print('something')。这就是为什么我很困惑。他说他使用的是 python3,但使用的是 python 2 打印语法。
【解决方案2】:

对于 Python 3,尝试用简单的“input()”替换所有“raw_input()”,它已经替换了“raw_input()”

【讨论】:

    猜你喜欢
    • 2015-05-01
    • 2013-04-06
    • 2011-12-04
    • 2016-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-16
    • 1970-01-01
    相关资源
    最近更新 更多