正在学习

3.1 Writing Effective Prompts for Code Generation

In-memory user storage

users_db: List[dict] = []

Define request body schema

class UserCreate(BaseModel):

username: str

email: EmailStr

password: str

@app.post("/register")

async def register_user(request: UserCreate):

"""Registers a new user with hashed password."""

# Check if user already exists

for user in users_db:

    if user["email"] == request.email:

        raise HTTPException(status_code=400, detail="Email already registered")

# Hash password

hashed_password = bcrypt.hashpw(request.password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')

# Store user record

user_data = {"username": request.username, "email": request.email, "password": hashed_password}

users_db.append(user_data)

return {"message": f"User {request.username} registered successfully"}

This code runs as-is in a Python 3.11 environment with FastAPI and bcrypt installed. It includes inline documentation, follows good practices, and demonstrates exactly how Claude uses context from your prompt to structure logic, validate inputs, and manage state.

If your prompt had simply said “create a register API”, Claude might have omitted password hashing or error handling. Every missing detail weakens its reasoning process.

Clarification Table

The table below summarizes key prompt components that help Claude generate high-quality results:

| Prompt Component | Purpose | Example |
| --- | --- | --- |
| Objective | Tells Claude what to build | “Build a FastAPI /registe r endpoint” |
| Language/Framework | Guides code syntax and dependencies | “Use Python 3.11 with FastAPI and bcrypt” |
| Behavioral Context | Defines expected logic or rules | “Validate input, hash passwords, handle duplicates” |
| Output Format | Controls structure of the output | “Return JSON response with success message” |
| Documentation Request | Improves readability and understanding | “Include docstrings and inline comments” |

By following this framework, you teach Claude how to think about your request rather than what to copy from its training data.

Effective prompting is about precision through clarity. Claude Code performs at its best when it understands not just the technical request but also the intention behind it. Every word in your prompt acts as a design decision: specify behavior, guide reasoning, and define format. By practicing this level of intentionality, you turn Claude into a disciplined coding partner rather than a generic assistant.

## 3.2 Step-by-Step and Chain-of-Thought Techniques
Claude Code isn’t just a code generator—it’s a reasoning partner. When you learn to guide it through problems step by step, it behaves like a senior engineer: thinking, planning, and validating before it writes a single line. This process is called chain-of-thought prompting, and it transforms how Claude approaches complex coding tasks. Rather than rushing to output, Claude breaks down your request into smaller logical steps, reasons through each part, and then produces complete, accurate, and maintainable code. Understanding and applying this technique will allow you to unlock Claude’s most advanced reasoning capabilities in real-world development.

Concept Development

In technical terms, chain-of-thought prompting instructs Claude to simulate the same cognitive process developers follow when solving a problem. It involves two key stages: reasoning and implementation.

During the reasoning stage, Claude examines the request, outlines a logical approach, and identifies dependencies or potential pitfalls. In the implementation stage, it translates that reasoning into structured, executable code. This two-phase pattern makes Claude’s responses both accurate and explainable.

For example, a prompt like “Write a Python function to calculate compound interest” might yield quick code that works but lacks explanation or input validation. However, if you ask Claude to “explain its reasoning first, then write the function,” it pauses to outline the formula, expected inputs, and steps—producing more consistent and robust results.

This approach mirrors the workflow of a thoughtful developer. You first outline logic, test assumptions, and only then write implementation code. With Claude, that same mental discipline is enforced through careful prompting.

Hands-On Example

To see this in practice, let’s build a small FastAPI service that calculates the factorial of a number. We’ll craft a prompt that activates Claude’s reasoning process before it writes the implementation.

Prompt

“Claude, before coding, outline your reasoning for creating a FastAPI endpoint that accepts a number as input and returns its factorial. Then, write the complete implementation with input validation, comments, and clear error handling.”

Claude’s Reasoning (Expected Response)

Claude will usually begin by breaking the problem into steps:

1. Define the FastAPI app and input schema.
2. Implement a factorial function with recursion and error checks.
3. Handle invalid inputs such as negative numbers.
4. Create an endpoint/factorial that validates input and returns JSON output.

Once this outline is complete, Claude generates the following code.

Resulting Code

```python
from fastapi import FastAPI, HTTPException

from pydantic import BaseModel

app = FastAPI()

练习题

What is the purpose of the users_db variable in the given code?

A. To store the API key for authentication
B. To store user data in memory
C. To track the number of registered users
D. To validate user emails

Which decorator is used to define the /register endpoint in FastAPI?

A. @app.get
B. @app.put
C. @app.post
D. @app.delete

What checks are performed during user registration in the given code?

A. Validate the username format
B. Check if the email is already registered
C. Verify the password strength
D. Hash the password before storage

The hashed_password is stored as a byte string in the users_db.

The user data is stored in users_db as a ___.

What is the purpose of the HTTPException raised in the registration endpoint?

What is the response returned after successful user registration?

A. The hashed password
B. The user's email
C. A success message with the username
D. The entire user record

Which knowledge points are involved in the chain-of-thought process for user registration?

A. In-memory User Storage Initialization
B. Chain-of-Thought Reasoning Stage
C. Password Hashing Implementation
D. Chain-of-Thought Implementation Stage

The UserCreate class defines the schema for the request body, including the user's password.

How does the code ensure password security during storage?

When implementing a user registration endpoint, what is the primary purpose of the duplicate check logic?

A. To ensure the password is hashed correctly
B. To prevent storing the same user multiple times
C. To validate the email format
D. To generate a success response message

Which components are essential for creating an effective prompt for Claude to generate a user registration endpoint? Select all that apply.

A. Objective: 'Build a FastAPI /register endpoint'
B. Language/Framework: 'Use Python 3.11 with FastAPI and bcrypt'
C. Output Format: 'Return JSON response with success message'
D. Documentation Request: 'Include inline comments'
E. Behavioral Context: 'Validate input, hash passwords, handle duplicates'

The chain-of-thought reasoning stage for implementing a user registration endpoint would involve identifying dependencies like the need for bcrypt for password hashing before writing any code.

In the user registration endpoint, the ___ method is used to iterate through the users_db list to check for duplicate emails.

登录后解锁笔记、知识点解析、AI 问答

立即登录