脚本在 shell 中有效,但不适用于 IDLE 文件

Script works in shell but not as IDLE file

当在 shell 上逐行执行以下代码时,它给出了预期的输出:

>>> name=input("Please give your full name : ")
Please give your full name : ins vikranth
>>> ListName=name.split(' ')
>>> outputString=ListName[1]+' '+ListName[0]
>>> print(outputString)
vikranth ins

代码不是作为文件总共 运行,而是在 shell 上逐行运行。 代码是:

name=input("Please give your full name : ")
ListName=name.split(' ')
outputString=ListName[1]+' '+ListName[0]
print(outputString)

错误信息是:

Please give your full name : ins vikranth
Traceback (most recent call last):
  File "ReverseName.py", line 1, in <module>
    name=input("Please give your full name
  File "<string>", line 1
    ins vikranth
               ^
SyntaxError: unexpected EOF while parsing

为什么会这样?

@Babu 兄弟代码对我来说似乎没问题,但你可能会忘记 somepoint.If person have a middle name 它会导致错误。当用户键入超过 2 个单词时,您有 2 个数组位置,它会由于缺少位置而导致文件意外结束,例如足球运动员 Kevin Prince Boateng。您可能想查看此 https://docs.python.org/2/c-api/memory.html 以了解动态内存管理

发生这种情况的原因是您的 python 版本...您的 IDLE 是 python 3.X,而您的文件正在 "translated"(解释)使用 python 2.X。 .. 所以有 2 个简单的解决方案:

1/ 坚持使用 python 3.X - 您的代码不会更改,只需更改解释器

2/ 编辑它以兼容 python 2.X :

name=raw_input("Please give your full name : ")

这里还有2个在线编译器,你可以从中看出区别:

Python 3.7 -> https://www.onlinegdb.com/online_python_compiler

Python 2.7 -> https://repl.it/languages/python