![](/img/trans.png)
[英]Simple HTTP response: why does this work with Python2 but not with Python3
[英]Why does the following code not work on python2?
以下代碼在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)
對於Python 2, input()
必須是raw_input()
。
“ PEP 3111:raw_input()被重命名為input()。也就是說,新的input()函數從sys.stdin中讀取一行,並以尾隨的換行符刪除該行。如果輸入過早終止,則會引發EOFError。要獲得input()的舊行為,請使用eval(input())。”
而且,正如cdarke指出的那樣,打印語句不應在要打印的項目周圍帶有括號。
在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
代替input
或raw_input
。 雖然不是很漂亮,但通常最好只使用一個Python版本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.