1

So in my code i want to do this structure

Mix the , , , and together.

I have this code

import random

ingredient = ['flour', 'baking powder', 'butter', 'milk', 'eggs', 'vanilla', 'sugar']

def create_recipe(main_ingredient, baking, measure, ingredient):
    """Create a random recipe and print it."""
    m_ingredient = random.choice(main_ingredient) #random choice from the main ingredient
    baking_ = random.choice(baking) #random choice from the baking list
    ingredients = random.choice(ingredient) #random choice from the ingredient list

    print("***", m_ingredient.title(), baking_.title() , "Recipe ***")
    print("Ingredients:")
    print(random.randint(1,3), random.choice(measure), m_ingredient)
    for i in range(len(ingredients)): #get the random ingredients
        print(random.randint(1,3), random.choice(measure), ingredient[i])
    print ("Method:")

    selected=[] # this is where the ingredients from the recipe
    selected_items = "Mix the"
    for i in range(len(ingredients)):
        ingredients= str(random.choice(ingredient))
        selected.append(ingredients)
    selected.insert(-2,'and')
    print(selected_items,",".join(selected), "together.") 

I had this as an output for it.

Mix the eggs,baking powder,sugar,and,flour,sugar together.

How do i add the put the 'and' before the last item in the list and make it just like the structure that i wanted?

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
prvrlx
  • 91
  • 8

1 Answers1

0

Put all your ingredients into a list and slice it according to your choosen string formatting:

things = ['flour', 'baking powder', 'butter', 'milk', 'eggs', 'vanilla', 'sugar']

# join all but the last element using ", " as seperator, then print the last element
# after the "and"    
print(f"You need {', '.join(things[:-1])} and {things[-1]}")

# or

print("You need", ', '.join(things[:-1]), "and", things[-1])

Output:

You need flour, baking powder, butter, milk, eggs, vanilla and sugar

Further resources:

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • what if i had an randomize list and it give me random list? should i do that aswell? – prvrlx Apr 06 '20 at 06:16
  • did you read about the slice notation? the statement does not care how many things are in your ist or if it is randomized -it takes all but the last and joins it, puts "and" and then the last element. Caveat for cooking though: there is general a "good" order in a receipt. f.e. Mix flour, baking powder, and valilla sugar. In a seperate bowl place the butter and sugar, mix both on high churning until color changes from yellow to white and fluffy, mix dry and butter and add the other wet ingredients etc - probably not going to happen with random lists ;o) – Patrick Artner Apr 06 '20 at 06:21
  • 1
    @prvlx for more see https://cooking.stackexchange.com/questions/tagged/baking ;o) – Patrick Artner Apr 06 '20 at 06:22