Reputation: 41
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)
Upvotes: 1
Views: 54
Reputation: 44404
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.
Upvotes: 1
Reputation: 721
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.
Upvotes: 1