简体   繁体   中英

Why does the following code not work on python2?

The following code works fine on python3 but not on python2? Please help me out. I tried running python3 form terminal. But when I run it through IDE it runs python2 and shows error. It shows error at the statement 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)

input() needs to be raw_input() for Python 2.

This was documented in the Python 3 change logs :

"PEP 3111: raw_input() was renamed to input(). That is, the new input() function reads a line from sys.stdin and returns it with the trailing newline stripped. It raises EOFError if the input is terminated prematurely. To get the old behavior of input(), use eval(input())."

Also, as cdarke pointed out, print statements shouldn't have parentheses around the item to print.

In Python 2 input is used for a different purpose, you should use raw_input in Python 2.

In addition, your print should not use parentheses. In Python 3 print is a function whereas in Python 2 it is a statement. Alternatively:

from __future__ import print_function

In this case you can achieve some portability with something like this:

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

Then use userinput instead of input or raw_input . Its not pretty though, and generally it is best to stick with just one Python version.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM