Generate Python code and Jupyter notebooks for course assignments. Use when (1) user asks to generate code for lab/assignment, (2) mentions "生成代码" or "generate code", (3) needs to create .py or .ipynb files for coursework.
Generate well-structured, self-documenting Python code for course assignments that meets academic requirements.
Before generating code:
Student Information:
Read student information from .env.local in workspace root:
NAME - Student nameNUMBER - Student numberEMAIL - Student email (optional)Use python-dotenv to load environment variables at the start of the script.
For Python scripts (.py):
Use the template at templates/ml_lab_template.py as base.
"""
CST8506 Lab [N]: [Title]
Author: Peng Wang
Student Number: 041107730
[Brief description]
"""
import os
# ... other imports
# 配置常量
# Configuration Constants
RANDOM_STATE = 42
OUTPUT_DIR = 'lab[n]_images'
os.makedirs(OUTPUT_DIR, exist_ok=True)
# ============================================================
# 步骤1:[步骤标题]
# Step 1: [Step Title]
# ============================================================
print("Step 1: [Step Title]")
print("-" * 40)
# [中文注释]
# [English comment]
# code here
print()
⚠️ PRINCIPLE 1: Raw Data Integrity
When printing datasets or statistics, always show the original form of the data.
0, 1) to string names (e.g., class_0) inside the script for the "Statistics" step.⚠️ PRINCIPLE 2: Concise and Aligned Output
print("=" * 80)
print("Step N: Step Title")
print("=" * 80)
pd.set_option('display.max_columns', None), pd.set_option('display.width', 1000), and pd.set_option('display.expand_frame_repr', False) to ensure all data columns are visible in a single block.output.txt) BEFORE generating screenshots.Example of Precise Output:
# ✅ GOOD - Precision for "Step 2: Dataset Statistics"
import pandas as pd
pd.set_option('display.max_columns', None)
pd.set_option('display.width', 1000)
pd.set_option('display.expand_frame_repr', False)
print("=" * 80)
print("Step 2: Print dataset statistics")
print("=" * 80)
print(f"Number of instances: {X.shape[0]}")
print(f"Number of attributes: {X.shape[1]}")
print(df.head())
Do NOT include:
# ❌ BAD - Results as raw arrays
print(f"Accuracy: {accuracy}")
print(f"Confusion Matrix: {cm}")
# ✅ GOOD - Formatted results table
from tabulate import tabulate
print("Step 10: Results table with accuracies and confusion matrices")
print("-" * 40)
results_table = []
for name, acc, cm in results:
results_table.append([name, f"{acc:.4f}", str(cm.tolist())])
headers = ["Model", "Accuracy", "Confusion Matrix"]
print(tabulate(results_table, headers=headers, tablefmt="simple"))
Required Dependencies for Formatted Output:
from tabulate import tabulate # For formatted tables
import pandas as pd # For DataFrame display
Do NOT include:
_wine_dataset:)Default Parameter Documentation:
When using algorithms with default parameters, ALWAYS print them:
# ✅ GOOD - Document default parameters
print(f"SVM with Linear kernel")
print(f" C (regularization): 1.0 (default)")
print(f" - Higher C = less regularization, may overfit")
print(f" - Lower C = more regularization, may underfit")
For Jupyter Notebooks (.ipynb):
.env.local and print headerFor detailed structure examples: See references/structure-examples.md
Self-Documenting Code:
Function Usage:
Comments (Bilingual):
Follow dev-code_comment skill for bilingual comments:
Example:
# 使用StandardScaler标准化数据
# Use StandardScaler to standardize data
# 原因:SVM对特征尺度敏感
# Reason: SVM is sensitive to feature scales
scaler = StandardScaler()
Avoid AI Appearance:
For detailed principles and examples: See references/code-principles.md
For pattern details: See references/common-patterns.md
Required Package:
Ensure python-dotenv is available for loading .env.local:
from dotenv import load_dotenv
import os
load_dotenv('.env.local')
STUDENT_NAME = os.getenv('NAME', '[Your Name]')
STUDENT_NUMBER = os.getenv('NUMBER', '[Your Student Number]')
Date Formatting:
Use datetime for current date:
from datetime import datetime
current_date = datetime.now().strftime('%Y-%m-%d')
Bilingual Comments (Chinese + English):
CRITICAL: Do NOT include internal logging or screenshot code in scripts.
Logger or OutputCapture classes in the coursework script.output.txt for verification and screenshots.
uv run python lab[n]_*.py > lab[n]_images/output.txt 2>&1
Never include:
OutputCapture or Logger classessave_code_screenshot() functionsStringIO or screenshot-related importsstdout internallyKeep assignment code focused on:
plt.savefig() for plots)For screenshot generation: Use the learning-code_screenshot skill separately.
⚠️ IMPORTANT: Submission reminders are for debugging purposes ONLY.
The reminder section should:
generate_output_screenshots.py which captures step-by-step output, not the entire run)# Only print reminder after all steps are complete (debugging only)
print()
print("=" * 60)
print("Reminder:")
print("1. Take screenshots of code from Google Colab")
print("2. Paste screenshots into Lab1AnswerTemplate.md")
print("3. Fill in descriptions for each step")
print("4. Convert markdown to .docx for submission")
print("=" * 60)
Note: When generating output screenshots with learning-code_screenshot skill, each step's output is captured separately, so submission reminders won't appear in the screenshots.
After generating code, check:
Documentation:
.env.local using python-dotenvdatetimeCode Quality:
learning-code_screenshot skill)Requirements:
For detailed validation checklist: See references/validation-guide.md
learning-code_screenshot skill)For more examples: See references/code-principles.md