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.

Easy Python 3.9+ Aug 9, 2026 AI & LLM integration patterns 16 views 0 copies

Python code

33 lines
Python 3.9+
def 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

stdout
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

  1. Use a regex to parse the expression instead of splitting on whitespace
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from AI & LLM integration patterns

Related tutorials and quizzes for this topic.