为什么下面的代码不适用于python2?

时间:2015-03-23 18:53:00

标签: python

以下代码在python3上运行正常但在python2上运行不正常?请帮帮我。我试过运行python3表单终端。但是,当我通过IDE运行它时,它运行python2并显示错误。它在语句input()处显示错误。

def addItem(listOfItems, itemInTheList):
    listOfItems.append(itemInTheList)


def showItems(listOfItems):
    length = len(listOfItems)-1
    while length >= 0:
        print("{}\n".format(listOfItems[length]))
        length -= 1
        continue


print("Enter the name of Items: ")
print("Enter DONE when done!")

listOfItems = list()

while True:
    x = input(" > ")
    if x == "DONE":
        break
    else:
        addItem(listOfItems, x)


showItems(listOfItems)

2 个答案:

答案 0 :(得分:1)

对于Python 2,

input()需要raw_input()

Python 3 change logs

中记录了这一点

" PEP 3111:raw_input()被重命名为input()。也就是说,新的input()函数从sys.stdin读取一行并返回它,并删除尾随的换行符。如果输入提前终止,它会引发EOFError。要获得input()的旧行为,请使用eval(input())。"

另外,正如cdarke指出的那样,打印语句不应该在要打印的项目周围加上括号。

答案 1 :(得分:1)

在Python 2 input用于不同目的,您应该在Python 2中使用raw_input

此外,您的print不应使用括号。在Python 3中print是一个函数,而在Python 2中它是一个语句。可替换地:

from __future__ import print_function

在这种情况下,您可以通过以下方式实现一些可移植性:

import sys
if sys.version_info[0] == 2:  # Not named on 2.6
    from __future__ import print_function
    userinput = raw_input
else:
    userinput = input

然后使用userinput代替inputraw_input。它虽然不漂亮,但通常最好只使用一个Python版本。

相关问题