基于for循环的数字列表,看看用户输入是否在列表中?

时间:2017-02-08 18:14:16

标签: python

好的,所以我尝试做两件事让我快速发布我的代码:

def main():

    animals = ["Monkey", "Parrot", "Dog", "Koala", "Giraffe"]
    favAnimal = input("What is your favorite animal?")

    print("What is your favorite animal?")
    if(favAnimal == animals):
        print("The " + favAnimal + " is both of our favorite's!")
    else:
        print("We don't like any of the same animals. D;")

    number= 1
    for n in range(0, 5):
        print(number + "." + animals[n])
        number=number+1

main()

因此,在if语句中,我试图弄清楚如何检查用户输入是否与动物列表中的任何项目相同,以及是否打印该语句。

我试图做的另一件事是在for循环中我用这样的升序打印动物列表:

  1. 鹦鹉 3 ...等
  2. 我尝试过不同的东西,但是没有任何东西可以用于for循环它一直说我需要添加int或float到第18行(打印数字行)但是当我这样做时似乎没有工作

    任何人都可以帮我解决这个问题吗?

5 个答案:

答案 0 :(得分:1)

您可以使用此修复代码(使用Python 2.7.x):

def main():

    animals = ["Monkey", "Parrot", "Dog", "Koala", "Giraffe"]
    favAnimal = raw_input("What is your favorite animal?")

    print("What is your favorite animal?")
    if favAnimal in animals:
        print("The " + favAnimal + " is both of our favorite's!")
    else:
        print("We don't like any of the same animals. D;")

    for n in range(0, 5):
        print(str(n+1) + ". " + animals[n])

main()

答案 1 :(得分:1)

可以使用" in"来修复if语句。操作者:

if favAnimal in animals:
    print("The " + favAnimal + " is both of our favorite's!")
else:
    print("We don't like any of the same animals. D;")

float / int的错误是因为你不能在输出中添加字符串和数字。如果您只是从以下位置更改print语句:

    print(number + "." + animals[n])

要:

    print(str(number) + "." + animals[n])

一切都应该没问题。

答案 2 :(得分:1)

if __name__ == "__main__":
    animals = ["Monkey", "Parrot", "Dog", "Koala", "Giraffe"]
    # Make sure the 'animals' data is capitalized, because there could have been a typo
    animals = [animal.capitalize() for animal in animals]

    # Python's most followed style guide, PEP8, recommends 'lowercase_with_underscores' 
    #for method names and instance variables. See:
    # https://www.python.org/dev/peps/pep-0008/#method-names-and-instance-variables

    # Also, we treat the user's input with .capitalize()
    favorite_animal = input("What is your favorite animal? ").capitalize()

    if favorite_animal in animals:
        # See 'format' method: https://docs.python.org/3.6/library/stdtypes.html#str.format
        print("The {} is in both of our favorite's!".format(favorite_animal))
    else:
        print("We don't like any of the same animals. D;")

    # See accessing index in 'for' loops:
    # http://stackoverflow.com/questions/522563/accessing-the-index-in-python-for-loops
    for i, animal in enumerate(animals):
        print("{}. {}".format(i + 1, animal))

答案 3 :(得分:0)

从打印声明中删除+个符号。

+符号替换为,

print(number,".", animals[n])

或者您也可以将打印声明更改为

print(str(number)+"."+ str(animals[n]))

答案 4 :(得分:0)

要考虑的一件事是,用户可以输入动物的名称,包括全部小写,全部大写或其他字母组合。

因此,检查动物是否存在于列表中的推荐方法是:

if favAnimal.lower() in [x.lower() for x in animals]: