检查列表中用户raw_input的元素数

时间:2014-01-17 23:33:27

标签: python list elements raw-input

我在python上相当新,我在尝试一些想法时遇到了以下问题: 我希望用户为蛋糕输入5种成分并将其存储在列表中并将列表返回给用户。 我告诉用户告诉我5种成分。 现在我想要python检查用户是否真的给了我5个成分或者给他们一个错误信息。 这是我到目前为止所做的。

def recipe():
    #create a list to store the recipe ingredients.
    print "Enter 5 ingredients that could possibly go into a cake: "
    recipeList = []
    ingredients = raw_input("> ")
    recipeList = recipeList.append(ingredients)

    recipeList = [ingredients]

    print recipeList

    if len(ingredients) = 5:
        print "Thanks"
    elif len(ingredients) > 5:
    print "That's too much"
    elif len(ingredients) < 5:
    print "That's too little"
    else:
        print "There's something wrong!"

recipe()

4 个答案:

答案 0 :(得分:2)

很多这些线都是多余的。你只需要这样的东西*:

def recipe():
    """Create a list to store the recipe ingredients."""

    print "Enter 5 ingredients that could possibly go into a cake: "
    ingredients = raw_input("> ").split()
    print ingredients

    if len(ingredients) == 5:
        print "Thanks"
    elif len(ingredients) > 5:
        print "That's too much"
    elif len(ingredients) < 5:
        print "That's too little"
    else:
        print "There's something wrong!"

recipe()

这里最重要的一点是:

ingredients = raw_input("> ").split()

它基本上做了两件事:

  1. 使用raw_input获取输入。

  2. 使用str.split拆分空格上的输入。结果将是一个子串列表(成分)。

  3. 另外,如果您想知道,我会将您在函数顶部的评论转换为正确的docstring


    *注意:我认为成分会被空格分开。但是,如果您希望将它们用不同的东西分隔,例如逗号,那么您可以为str.split指定一个特定的分隔符:

    ingredients = raw_input("> ").split(",")
    

答案 1 :(得分:0)

如果你的所有成分都是一个单词,它们将在逻辑上用空格分隔,所以你需要做的就是split每个空间的输入字符串。或者您可以指定每个成分需要用逗号或某种分隔符分隔split(",")

print "Enter 5 ingredients that could possibly go into a cake: "

    recipeList = raw_input("> ").split(" ")

等于运算符是==

if len(recipeList ) == 5:

答案 2 :(得分:0)

您需要使用split函数,因为raw_input不会按空格或任何其他分隔符分隔输入。

recipeList = ingredients.split()

此外,这个比较应该是双等于,否则它是一个赋值。此外,它应该比较列表的长度,而不是用户输入。

if len(recipeList) == 5:

答案 3 :(得分:0)

这就行了:

def recipe():
    #create a list to store the recipe ingredients.
    print "Enter 5 ingredients that could possibly go into a cake: "
    recipeList = []
    line = raw_input("> ")         # changed line

    ingredients = line.split()     # changed line, converts the input in an array
                                   # (input separated by spaces)

    recipeList = recipeList.append(ingredients)

    recipeList = [ingredients]

    print recipeList

    if len(ingredients) == 5:      # added the double equal
       print "Thanks"
    elif len(ingredients) > 5:
       print "That's too much"
    elif len(ingredients) < 5:
       print "That's too little"
    else:
       print "There's something wrong!"

recipe()