Conditional Statements
Learn how to add content based on conditions in your prompts
Overview
Conditional statements in PromptL enable dynamic and adaptive prompts. By incorporating logic into your prompts, you can:
- Tailor responses based on user input or context.
- Control the flow of conversations dynamically.
- Generate content conditionally for more personalized or complex interactions.
Conditionals are evaluated at runtime, ensuring that your prompts adapt seamlessly to the data provided.
Syntax
Conditional blocks in PromptL use the if
, else
, and endif
keywords, wrapped in {{ }}
. The content within the block is processed only if the condition evaluates to true
.
Basic Syntax
Example: Simple Conditional
Advanced Usage
Checking Variable Existence
You can use conditionals to check if a variable is defined before using it.
Nested Conditions
Conditionals can be nested to handle more complex logic.
Using Expressions in Conditions
Conditions can include complex expressions, such as combining variables or performing calculations.
Best Practices
- Keep It Simple: Avoid deeply nested conditionals. Break complex logic into smaller, reusable components.
- Define Default Values: Ensure variables have defaults (
||
) to prevent unexpected errors. - Test Edge Cases: Check how your logic handles undefined variables or null values.
- Use Readable Conditions: Use descriptive variable names and straightforward logic to improve maintainability.
- ✅ Good:
{{ if user_logged_in && has_permission }}
- ❌ Bad:
{{ if x > 0 || y == 1 }}
- ✅ Good:
Debugging Conditionals
If your conditional logic isn’t behaving as expected:
- Verify Variable Values: Check if the variables used in your condition are defined and contain the expected data.
- Simplify Conditions: Break down complex expressions into smaller, testable conditions.
- Add Debug Statements: Temporarily output variable values for troubleshooting:
Advanced Example
Here’s a real-world example of a conditional block for a personalized travel assistant:
Summary
Conditional statements are a powerful tool in PromptL, enabling dynamic and personalized prompts that adapt to user input and context. By combining them with variables and expressions, you can build highly responsive and flexible conversations.
Next: Learn about Loops and Iteration for even more dynamic capabilities.