印刷品;无”;当我运行it/PYTHON时
运行此代码时,我会询问用户是否希望代码按相反顺序运行 一切都运行顺利,但是当程序运行部分印刷品;无”;当我运行it/PYTHON时,python,Python,运行此代码时,我会询问用户是否希望代码按相反顺序运行 一切都运行顺利,但是当程序运行部分时,是否需要逆序(y/n),出于某种原因,它会在下一行打印None 有人能解释一下我为什么/如何让这一切停止吗 def farmList(): print("Please enter six farming animals: ") terms = [] for counter in range(6): term = input("Please enter a farm
时,是否需要逆序(y/n)
,出于某种原因,它会在下一行打印None
有人能解释一下我为什么/如何让这一切停止吗
def farmList():
print("Please enter six farming animals: ")
terms = []
for counter in range(6):
term = input("Please enter a farm animal")
terms.append(term)
reverseOrder = input("Do you want reverse order (y/n)")
if reverseOrder == "y":
print(terms[::-1])
else:
print(terms)
whichTerm = int(input("Choose a number between 1-6, and the program will print that animal: "))
print(terms[whichTerm-1])
您的代码运行良好,至少在Python3中是如此(有关更多信息,请参阅此线程:) 请注意,您只显示一个反向列表,而不反向显示术语,尽管:
Please enter six farming animals:
Please enter a farm animala
Please enter a farm animalb
Please enter a farm animalc
Please enter a farm animald
Please enter a farm animale
Please enter a farm animalf
Do you want reverse order (y/n)y
['f', 'e', 'd', 'c', 'b', 'a']
Choose a number between 1-6, and the program will print that animal: 1
a
要反转列表,您可以编写:
if reverseOrder == "y":
terms = terms[::-1]
因此,您的代码将变成:
def farmList():
print("Please enter six farming animals: ")
terms = []
for counter in range(6):
term = input("Please enter a farm animal")
terms.append(term)
reverseOrder = input("Do you want reverse order (y/n)")
if reverseOrder == "y":
terms = terms[::-1]
whichTerm = int(input("Choose a number between 1-6, and the program will print that animal: "))
print(terms[whichTerm-1])
farmList()
对于Python2.7,如果正确地调用了
farmList()
,则将每次出现的input()
替换为raw\u input()
,然后将input
更改为raw\u input
应该适用于Python2.7。
对于Python2.7,raw_input()
准确地获取用户键入的内容,并将其作为字符串传回。
对于Python3,您的代码应该可以正常工作。对
farmList
的调用在哪里?您使用的Python版本是什么?您到底是如何运行的?您是否真的在某处显式调用了farmList()
?我正在运行Python 3.6.0 Shell。我将如何实现它?我应该只使用IF语句吗?谢谢你的建议,我没想过。