Search code examples
pythonlistelementraw-input

Check number of elements fromuser raw_input in a list


I'm fairly new at python and I'm stuck at the following problem, while trying out some ideas: I'd like users to enter 5 ingredients for a cake and store them in a list and give the list back to the user. I tell the user to tell me 5 ingredients. Now I would like python to check if the user really gave me 5 ingredients or otherwise give them an error message. This is what I've got so far.

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()

Solution

  • A lot of those lines are redundant. All you need is something like this*:

    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()
    

    The most important line here is this:

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

    It basically does two things:

    1. Gets the input with raw_input.

    2. Splits the input on spaces using str.split. The result will be a list of substrings (the ingredients).

    Also, if you are wondering, I made the comment at the top of your function into a proper docstring.


    *Note: I assumed that the ingredients would be separated by spaces. If however you want to have them separated by something different, such as a comma, then you can give str.split a specific delimiter:

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