为什么 input() 在我按回车键时会出错? [英] Why input() gives an error when I just press enter?

查看:127
本文介绍了为什么 input() 在我按回车键时会出错?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 python 代码:

I have the following python code:

print 'This is a simple game.'
input('Press enter to continue . . .')
print 'Choose an option:'

...

但是当我按下 Enter 按钮时,出现以下错误:

But when I press Enter button, I get the following error:

Traceback (most recent call last):
  File "E:/4.Python/temp.py", line 2, in <module>
    input('Press enter to continue . . .')
  File "<string>", line 0

   ^
SyntaxError: unexpected EOF while parsing

附言我在 Windows 7 上使用 python IDLE 2.6 版.

P.S. I am using python IDLE version 2.6 on Windows 7.

推荐答案

对于 Python 2,您需要 raw_input,而不是 input.前者会读一行.后者将读取一行并尝试执行它,如果您不希望您的代码被输入数据的人破坏,则不建议这样做.

For Python 2, you want raw_input, not input. The former will read a line. The latter will read a line and try to execute it, not advisable if you don't want your code being corrupted by the person entering data.

例如,他们可以执行诸如调用任意函数之类的操作,如下例所示:

For example, they could do something like call arbitrary functions, as per the following example:

def sety99():
    global y
    y = 99

y = 0
input ("Enter something: ")
print y

如果您在 Python 2 下运行该代码并输入 sety99(),输出将为 99,尽管事实上您的代码(在正常情况下)执行流程)有目的地将 y 设置为除零以外的任何值(它在函数中执行,但您的代码永远不会显式调用该函数).这样做的原因是 input(prompt) 调用等价于 eval(raw_input(prompt)).

If you run that code under Python 2 and enter sety99(), the output will 99, despite the fact that at no point does your code (in its normal execution flow) purposefully set y to anything other than zero (it does in the function but that function is never explicitly called by your code). The reason for this is that the input(prompt) call is equivalent to eval(raw_input(prompt)).

请参阅此处了解详细信息.

请记住,Python 3 解决了这个问题.输入函数的行为与您预期的一样.

Keep in mind that Python 3 fixes this. The input function there behaves as you would expect.

这篇关于为什么 input() 在我按回车键时会出错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆