Chain of Thought Prompting in Python: Step-by-Step Reasoning Demo
This demo shows how to structure a function that explains its own reasoning step-by-step, mimicking chain-of-thought prompting for AI systems.
Python code
33 linesdef solve_math_step_by_step(expression: str) -> str:
"""Solves a simple expression, showing each reasoning step."""
# Step 1: Parse the expression (assume "a + b" or "a - b")
parts = expression.split()
a = int(parts[0])
op = parts[1]
b = int(parts[2])
steps = []
steps.append(f"Step 1: Identify the operands → {a} and {b}")
steps.append(f"Step 2: Identify the operation → {op}")
if op == "+":
result = a + b
steps.append(f"Step 3: Compute {a} + {b} = {result}")
elif op == "-":
result = a - b
steps.append(f"Step 3: Compute {a} - {b} = {result}")
else:
raise ValueError("Only + and - supported")
steps.append(f"Final Answer: {result}")
return "\n".join(steps)
if __name__ == "__main__":
expr = "15 + 7"
print(f"Expression: {expr}\n")
print(solve_math_step_by_step(expr))
print("\n--- Another example ---\n")
expr2 = "20 - 9"
print(f"Expression: {expr2}\n")
print(solve_math_step_by_step(expr2))
Output
Expression: 15 + 7
Step 1: Identify the operands → 15 and 7
Step 2: Identify the operation → +
Step 3: Compute 15 + 7 = 22
Final Answer: 22
--- Another example ---
Expression: 20 - 9
Step 1: Identify the operands → 20 and 9
Step 2: Identify the operation → -
Step 3: Compute 20 - 9 = 11
Final Answer: 11
How it works
This function simulates chain-of-thought reasoning by explicitly logging each step of the solution process. It parses a simple two-operand expression, identifies operands and the operator, then computes and reports the result. The step-by-step output mirrors how modern LLMs are prompted to 'think out loud' before giving a final answer, which is a core pattern in AI integration. This structure is useful when building prompt chains or when explaining model reasoning to users.
Common mistakes
- Forgetting to handle input with uneven spaces or extra whitespace around operators
- Assuming only + and - operations, without checking for validation or fallback
- Not using an f-string consistently, leading to formatting errors in the steps output
Variations
- Use a regex to parse the expression instead of splitting on whitespace
- Add support for multiplication and division by extending the if-elif chain
Real-world use cases
- Building transparent AI assistants that show users how they arrived at an answer
- Creating debugging tools for LLM prompt chains to verify reasoning steps
- Teaching tool for developers learning how to structure model outputs with visible reasoning
Sponsored
More from AI & LLM integration patterns
- Cache LLM Completions by Hashing the Prompt in Python easy
- Circuit Breaker Pattern in Python for LLM API Calls medium
- Cosine Similarity to Retrieve Top K Chunks in Python easy
- Demonstrate Prompt Injection Bypass in Python easy
- How to Accumulate Streamed Tokens into a Final String in Python easy
- How to Append Few-Shot Examples to a Prompt in Python easy
Keep learning
Related tutorials and quizzes for this topic.