← Building with AI

Templates with options and lists

Add optional parts and turn lists into readable prompt text.

Start this lesson

Real prompts often have parts that are only sometimes needed (a diet, a reading level) and lists of items (ingredients, notes, questions). Build the prompt step by step: start with the main instruction, add each optional part only if it was given, and turn lists into text with join. The result is one clean string to send.

def recipe_prompt(ingredients, diet=None):
    prompt = "Suggest one dinner I can cook using: " + ", ".join(ingredients) + "."
    if diet:
        prompt += f" It must be {diet}."
    return prompt

print(recipe_prompt(["rice", "beans", "peppers"]))
print(recipe_prompt(["eggs", "spinach"], diet="vegetarian"))

", ".join(list) puts the items together with a comma between them. diet=None makes diet optional.

To make a bullet list, join with a newline and a dash: "\n".join("- " + item for item in items). Models read bullet lists well.

Keep templates as plain functions that return strings. Then you can print and test them without calling a model at all.