为什么下面的代码在python2上不起作用?

2024-10-03 23:25:32 发布

您现在位置: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)

Tags: 代码inputdef错误lengthpython3printenter
2条回答

对于python2,input()需要是raw_input()。你知道吗

这在Python 3 change logs中有记载:

“PEP 3111:原始输入()已重命名为输入()。也就是说,new input()函数从系统标准返回它并去掉尾随的换行符。如果输入过早终止,则会引发EOR。要获取input()的旧行为,请使用eval(input())。”

另外,正如cdarke所指出的,print语句不应该在要打印的项周围加括号。你知道吗

在python2中input用于不同的目的,您应该在python2中使用raw_input。你知道吗

此外,您的print不应该使用括号。在python3中print是一个函数,而在python2中它是一个语句。或者:

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版本。你知道吗

相关问题 更多 >