# Step-by-Step Reasoning (Chain of Thought) — Prompt Engineering

Source: https://www.geekswithgeeks.com/en/prompt-engineering/r-cot

> Ask for intermediate steps on problems that need them.

## Space to work it out

For multi-step problems (arithmetic, logic, planning, code analysis) accuracy often improves when the model **writes out intermediate steps** before the answer, because each generated step becomes context for the next one. Typical phrasing: "Work through this step by step, then give the final answer on a line starting with `Final answer:`". Putting the answer on a fixed line makes it easy to **parse**. Note that newer **reasoning models** do this internally, and for them forcing long visible steps may add nothing; check your model's guidance. Never treat the explanation as proof: a fluent chain can still contain a wrong step.

## Think in steps, check the result

Complex tasks improve when broken into steps, sampled several times or verified.

![Four tools: step-by-step, vote, chain, verify.](assets/figures/prompt-engineering/section-3-map.svg) — Figure 3.1 — Step-by-step, vote, chain and verify.

## Parsing a step-by-step reply, run

I ran this plain-Python (standard library only) example. The reply (written by hand to illustrate the format) shows steps and a `Final answer:` line. The code extracts 54 and independently recomputes 12 x 5 minus 10% = 54.0.

```python
import re

reply = """Step 1: 12 pens at 5 rupees each cost 12 * 5 = 60.
Step 2: A 10 percent discount is 6.
Step 3: 60 - 6 = 54.
Final answer: 54"""

m = re.search(r"Final answer:\s*(\d+)", reply)
print("parsed answer:", int(m.group(1)))
print("check:", 12 * 5 - 0.10 * (12 * 5))

```

Output:

```
parsed answer: 54
check: 54.0
```

## Verify with code when you can

For arithmetic and logic, recompute the answer in code instead of trusting the written steps.

**Quiz:** Why put the final answer on a fixed line?

- [x] So your code can parse it reliably
- [ ] To hide the reasoning
- [ ] To lower the price
- [ ] To skip the steps

*Answer:* So your code can parse it reliably. A predictable marker makes extraction simple.
