当我运行它/ PYTHON时打印“无”

时间:2017-03-26 12:11:46

标签: python

运行此代码,我询问用户是否需要相反的代码。

一切运行顺利,但是当程序运行Do you want reverse order (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])

2 个答案:

答案 0 :(得分:1)

如果您正确调用farmList(),则将input更改为raw_input应适用于python 2.7。 对于Python 2.7,raw_input()完全取用用户键入的内容并将其作为字符串传回。 另外,对于Python 3,您的代码应该可以正常工作。

答案 1 :(得分:0)

您的代码工作正常,至少在Python3中(有关详细信息,请参阅此主题:What's the difference between raw_input() and input() in python3.x

请注意,您只显示反向列表,但不要反转terms

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,将input()的每次出现都替换为raw_input()