第一次使用Claude Code
完成了安裝和認證,今天開始第一次實戰體驗。帶你從零開始完成第一個程式設計任務。
啟動Claude Code
基本啟動
開啟終端,輸入:
claude
首次啟動時,你會看到歡迎資訊:
╔════════════════════════════════════════════╗
║ ║
║ Welcome to Claude Code (Beta) ║
║ ║
║ Your AI-powered coding assistant ║
║ ║
╚════════════════════════════════════════════╝
Connected to: claude-3-7-sonnet-20250219
Working directory: /Users/username/project
How can I help you code today?
在特定專案中啟動
想在特定專案中使用Claude Code:
# 切换到项目目录
cd ~/my-project
# 启动Claude Code
claude
Claude Code會自動識別當前目錄作為工作目錄。
啟動選項
# 指定工作目录
claude --directory /path/to/project
# 指定模型
claude --model claude-3-opus
# 显示详细日志
claude --verbose
# 查看所有选项
claude --help
第一個任務:修改檔案
從簡單的任務開始:建立並修改一個Python指令碼。
步驟1:建立檔案
在Claude Code中輸入:
请创建一个名为hello.py的文件,内容是打印"Hello, Claude Code!"
Claude Code會:
- 理解你的意圖
- 建立檔案
- 寫入程式碼
- 顯示結果
你會看到類似的輸出:
I'll create a hello.py file for you.
📝 Creating: hello.py
✓ File created successfully
Content:
───────────────────────────────
print("Hello, Claude Code!")
───────────────────────────────
The file has been created in your current directory.
步驟2:驗證檔案
在另一個終端視窗(或暫時退出Claude Code),驗證檔案:
# 查看文件内容
cat hello.py
# 运行文件
python hello.py
# 输出: Hello, Claude Code!
步驟3:修改檔案
回到Claude Code,輸入:
请修改hello.py,添加一个函数来接收用户名并打印问候语
Claude Code會自動修改檔案:
def greet(name):
"""打印个性化的问候语"""
print(f"Hello, {name}! Welcome to Claude Code!")
if __name__ == "__main__":
import sys
if len(sys.argv) > 1:
name = sys.argv[1]
else:
name = "Friend"
greet(name)
第二個任務:理解現有程式碼
現在學習如何讓Claude Code理解和分析現有程式碼。
步驟1:請求程式碼分析
请分析hello.py的代码结构并解释它的工作原理
Claude Code會給出詳細分析:
Let me analyze the hello.py file:
📊 Code Structure Analysis
1. Function Definition
- greet(name): 接收一个name参数并打印问候语
- Uses f-string for formatting
- Includes docstring for documentation
2. Main Block
- Uses if __name__ == "__main__" pattern
- Imports sys module for command-line arguments
- Handles two scenarios:
a) User provides name as argument
b) No argument provided (defaults to "Friend")
3. How it works:
✓ User runs: python hello.py Alice
✓ sys.argv[1] captures "Alice"
✓ greet("Alice") is called
✓ Output: "Hello, Alice! Welcome to Claude Code!"
4. Best Practices Used:
✓ Function with clear purpose
✓ Docstring documentation
✓ Default value handling
✓ Main block guard
步驟2:請求改進建議
这段代码有什么可以改进的地方吗?
Claude Code會提供專業建議並可以直接實現改進。
第三個任務:除錯錯誤
學習如何使用Claude Code修復bug。
步驟1:建立有bug的程式碼
创建一个calculator.py文件,包含加减乘除四个函数
步驟2:引入一個錯誤
手動編輯檔案,在除法函式中引入除零錯誤:
def divide(a, b):
return a / b # 没有检查b是否为0
步驟3:請求Claude Code修復
在Claude Code中:
calculator.py的divide函数有问题,请帮我修复并添加错误处理
Claude Code會:
- 識別問題
- 提供修復方案
- 實現改進
def divide(a, b):
"""
除法运算,包含除零错误处理
Args:
a: 被除数
b: 除数
Returns:
除法结果
Raises:
ValueError: 当除数为0时
"""
if b == 0:
raise ValueError("除数不能为零")
return a / b
理解Claude Code的工作流程
1. 對話式互動
Claude Code透過自然語言對話理解你的意圖:
你: 创建一个Express服务器,监听3000端口
Claude: I'll create an Express server for you.
[创建server.js文件并实现代码]
你: 添加一个GET /api/hello路由
Claude: I'll add that route to your server.
[修改server.js,添加路由]
2. 上下文理解
Claude Code會記住對話歷史:
你: 创建一个User类,包含name和email属性
Claude: [创建User类]
你: 添加一个验证email格式的方法
Claude: I'll add an email validation method to the User class.
[自动找到User类并添加方法]
3. 自主探索
當你提出複雜需求時,Claude Code會:
- 自動探索專案結構
- 找到相關檔案
- 理解程式碼依賴關係
- 跨檔案進行修改
常用互動模式
模式1:直接命令
创建README.md文件
添加Git忽略规则
格式化所有Python文件
运行测试
模式2:詳細描述
我想创建一个React组件,用于显示用户列表。
组件需要:
1. 从API获取用户数据
2. 显示加载状态
3. 处理错误情况
4. 支持分页
模式3:增量改進
你: 创建一个简单的登录表单
Claude: [创建基础表单]
你: 添加表单验证
Claude: [添加验证逻辑]
你: 添加提交后的loading状态
Claude: [添加loading状态]
你: 美化样式
Claude: [添加CSS样式]
實用技巧
技巧1:明確你的需求
❌ 不好的提問:
写个函数
✅ 好的提問:
创建一个函数,接收用户ID,从数据库获取用户信息,
如果用户不存在返回null,包含错误处理
技巧2:分步驟進行
複雜任務分步驟更清晰:
第一步:创建数据模型
第二步:实现CRUD操作
第三步:添加单元测试
第四步:添加API路由
技巧3:提供上下文
我正在用Express和MongoDB开发一个博客系统。
请帮我创建文章(Post)模型,包含标题、内容、作者、创建时间等字段。
技巧4:請求解釋
请解释这段代码的工作原理
这个函数为什么这样写?
有更好的实现方式吗?
技巧5:使用深度思考
複雜問題,可以要求深度思考:
think hard: 如何优化这个查询性能?
ultrathink: 设计一个可扩展的微服务架构
多輪對話示例
看一個完整的多輪對話例項:
👤 你: 创建一个待办事项应用的后端API
🤖 Claude: I'll create a Todo API backend for you.
Let me start by setting up the project structure.
[创建文件:server.js, models/Todo.js, routes/todos.js]
✓ Created basic Express server
✓ Created Todo model with Mongoose
✓ Created CRUD routes for todos
────────────────────────────────────────────
👤 你: 添加用户认证功能
🤖 Claude: I'll add authentication to your Todo API.
[创建文件:models/User.js, middleware/auth.js, routes/auth.js]
[修改:todos.js routes to include authentication]
✓ Added User model
✓ Implemented JWT authentication
✓ Protected todo routes
✓ Added login/register endpoints
────────────────────────────────────────────
你: 添加单元测试
🤖 Claude: I'll add unit tests for your API.
[创建文件:tests/auth.test.js, tests/todos.test.js]
[修改:package.json to add test scripts]
✓ Added test suite with Jest
✓ Created tests for authentication
✓ Created tests for todo CRUD operations
✓ Added npm test script
────────────────────────────────────────────
👤 你: 创建API文档
🤖 Claude: I'll generate API documentation.
[创建文件:API.md, swagger.yaml]
✓ Created comprehensive API documentation
✓ Added Swagger/OpenAPI spec
✓ Documented all endpoints with examples
退出和重啟
退出Claude Code
# 输入exit或quit
exit
# 或使用快捷键
Ctrl + D (Linux/macOS)
Ctrl + C (所有平台)
儲存對話歷史
Claude Code會自動儲存對話歷史,下次啟動時可以繼續:
# 启动后,使用/history查看历史
claude
/history
下一步探索
完成第一次使用後:
-
學習更多命令
-
探索核心功能
-
嘗試實戰專案
-
進階配置
常見問題
Q: Claude Code沒有響應怎麼辦?
檢查網路連線,確認API金鑰有效:
claude --auth-status
Q: 如何檢視Claude Code建立或修改了哪些檔案?
使用Git檢視更改:
git status
git diff
Q: 可以撤銷Claude Code的修改嗎?
是的,使用Git:
git checkout -- filename # 撤销单个文件
git reset --hard # 撤销所有更改
Q: Claude Code會自動儲存檔案嗎?
是的,Claude Code會自動儲存所有修改。建議配合Git使用,方便回滾。
Q: 一次對話可以處理多少檔案?
Claude Code支援約200,000 tokens的上下文,可以同時處理幾十個檔案。
實用建議
-
配合Git使用
- 在使用Claude Code前先提交當前更改
- 方便回滾和檢視修改歷史
-
保持清晰溝通
- 明確表達你的需求
- 提供必要的上下文
- 分步驟處理複雜任務
-
驗證結果
- Claude Code很強大,但仍需驗證
- 執行測試確保程式碼正確
- 檢查生成的程式碼是否符合預期
-
利用多輪對話
- 不要期望一次就完美
- 透過多輪對話逐步完善
- 及時提供反饋
-
學習提示詞技巧
- 觀察什麼樣的提問得到更好的結果
- 積累你的提示詞模板
- 檢視 最佳實踐
總結
透過這第一次使用體驗,你應該已經:
✅ 瞭解如何啟動Claude Code ✅ 掌握基本的對話互動方式 ✅ 學會建立和修改檔案 ✅ 理解Claude Code的工作流程 ✅ 知道如何提出更好的問題
Claude Code是一個強大的AI程式設計助手,它會隨著你的使用越來越得心應手。繼續探索,享受AI賦能的程式設計體驗吧!