Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么我只按enter键时input()会出错?_Python - Fatal编程技术网

Python 为什么我只按enter键时input()会出错?

Python 为什么我只按enter键时input()会出错?,python,Python,我有以下python代码: print 'This is a simple game.' input('Press enter to continue . . .') print 'Choose an option:' ... 但当我按下Enter按钮时,我得到以下错误: 回溯(最近一次呼叫最后一次): 文件“E:/4.Python/temp.py”,第2行,在 输入('按enter键继续…') 文件“”,第0行 ^ SyntaxError:分析时出现意外的EOF 另外,我在Windows

我有以下python代码:

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

...
但当我按下Enter按钮时,我得到以下错误:

回溯(最近一次呼叫最后一次):
文件“E:/4.Python/temp.py”,第2行,在
输入('按enter键继续…')
文件“”,第0行
^
SyntaxError:分析时出现意外的EOF

另外,我在Windows 7上使用的是python IDLE 2.6版。

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

例如,他们可以调用任意函数,如下例所示:

def sety99():
    global y
    y = 99

y = 0
input ("Enter something: ")
print y
如果在Python 2下运行该代码并输入
sety99()
,则输出将
99
,尽管您的代码(在其正常执行流中)在任何时候都没有故意将
y
设置为零以外的任何值(它在函数中设置,但该函数从未被您的代码显式调用)。原因是
input(prompt)
调用相当于
eval(raw\u input(prompt))

有关血淋淋的详细信息,请参阅

请记住,Python3解决了这个问题。其行为与您预期的一样。

在Python 2中,将计算
input()
字符串,如果字符串为空,则引发异常。您可能需要
raw\u input()
(或者转到Python3)。

在Python2.x中,
input()
相当于
eval(raw\u input())
。当传递空字符串时,
eval
会给出语法错误


您希望改用
raw\u input()

如果在Python2.x上使用
input
,它将被解释为Python表达式,这不是您想要的。因为在您的例子中,字符串是空的,所以会引发一个错误


您需要的是
原始输入
。使用它,它将返回一个字符串

实际上,您不能在
eval
中分配任何内容。但是,您可以调用任何您想要的破坏性方法,因此它几乎没有什么更好的。或者,您想使用Python 3,其中
input()
执行Python 2
raw\u input()
所执行的操作。