Skip to content

Commit e572c7e

Browse files
MBimroseclaude
andcommitted
Add Python Tutorials section with in-browser code runner
Six interactive lessons under Code > Python Tutorials plus assets/python-runner.html, a Pyodide-based runner embedded in each lesson. Co-Authored-By: Claude Code <noreply@anthropic.com>
1 parent c3e5ea9 commit e572c7e

8 files changed

Lines changed: 855 additions & 0 deletions

File tree

‎assets/python-runner.html‎

Lines changed: 171 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,171 @@
1+
<!doctype html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="utf-8">
5+
<meta name="viewport" content="width=device-width, initial-scale=1">
6+
<title>Python Runner</title>
7+
<style>
8+
:root {
9+
--border: #d1d5db;
10+
--bg: #ffffff;
11+
--bar-bg: #f3f4f6;
12+
--out-bg: #1e1e1e;
13+
--out-fg: #d4d4d4;
14+
--accent: #2b6cb0;
15+
}
16+
@media (prefers-color-scheme: dark) {
17+
:root {
18+
--border: #4b5563;
19+
--bg: #1f2937;
20+
--bar-bg: #111827;
21+
--out-bg: #0d1117;
22+
--out-fg: #c9d1d9;
23+
}
24+
body { color: #e5e7eb; }
25+
}
26+
* { box-sizing: border-box; }
27+
body {
28+
margin: 0;
29+
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
30+
background: var(--bg);
31+
display: flex;
32+
flex-direction: column;
33+
height: 100vh;
34+
}
35+
.bar {
36+
display: flex;
37+
align-items: center;
38+
gap: 10px;
39+
padding: 6px 10px;
40+
background: var(--bar-bg);
41+
border-bottom: 1px solid var(--border);
42+
}
43+
button {
44+
background: var(--accent);
45+
color: #fff;
46+
border: none;
47+
border-radius: 6px;
48+
padding: 5px 14px;
49+
font-size: 14px;
50+
cursor: pointer;
51+
}
52+
button:disabled { opacity: 0.6; cursor: wait; }
53+
#resetbtn { background: transparent; border: 1px solid var(--border); color: inherit; }
54+
#status { font-size: 12px; opacity: 0.75; }
55+
textarea {
56+
flex: 1;
57+
width: 100%;
58+
border: none;
59+
resize: none;
60+
padding: 10px;
61+
font-family: ui-monospace, Consolas, "Cascadia Mono", monospace;
62+
font-size: 13.5px;
63+
line-height: 1.45;
64+
tab-size: 4;
65+
background: var(--bg);
66+
color: inherit;
67+
min-height: 90px;
68+
}
69+
textarea:focus { outline: 2px solid var(--accent); outline-offset: -2px; }
70+
pre {
71+
margin: 0;
72+
padding: 10px;
73+
background: var(--out-bg);
74+
color: var(--out-fg);
75+
font-family: ui-monospace, Consolas, "Cascadia Mono", monospace;
76+
font-size: 12.5px;
77+
line-height: 1.4;
78+
overflow: auto;
79+
min-height: 70px;
80+
max-height: 45%;
81+
border-top: 1px solid var(--border);
82+
white-space: pre-wrap;
83+
word-break: break-word;
84+
}
85+
</style>
86+
</head>
87+
<body>
88+
<div class="bar">
89+
<button id="run">&#9654; Run</button>
90+
<button id="resetbtn">Reset code</button>
91+
<span id="status">Edit the code, then press Run.</span>
92+
</div>
93+
<textarea id="code" spellcheck="false" aria-label="Python code editor"></textarea>
94+
<pre id="out" aria-label="Program output"></pre>
95+
96+
<script src="https://cdn.jsdelivr.net/pyodide/v0.26.4/full/pyodide.js"></script>
97+
<script>
98+
const codeEl = document.getElementById("code");
99+
const outEl = document.getElementById("out");
100+
const statusEl = document.getElementById("status");
101+
const runBtn = document.getElementById("run");
102+
const resetBtn = document.getElementById("resetbtn");
103+
104+
// Starter code arrives in the URL fragment so tutorial pages can embed
105+
// <iframe src=".../python-runner.html#<urlencoded code>">
106+
// or <iframe src=".../python-runner.html#b64:<base64 of code>"> (robust to #, %, <, etc.)
107+
function loadStarter() {
108+
const frag = decodeURIComponent(location.hash.slice(1));
109+
if (!frag) return 'print("Hello from Team 4096!")';
110+
if (frag.startsWith("b64:")) {
111+
try {
112+
return new TextDecoder().decode(
113+
Uint8Array.from(atob(frag.slice(4)), (c) => c.charCodeAt(0))
114+
);
115+
} catch (e) { /* fall through */ }
116+
}
117+
return frag;
118+
}
119+
const starter = loadStarter();
120+
codeEl.value = starter;
121+
122+
let pyodidePromise = null;
123+
function loadPython() {
124+
if (!pyodidePromise) {
125+
statusEl.textContent = "Loading Python in your browser (first run takes a few seconds)…";
126+
pyodidePromise = loadPyodide();
127+
pyodidePromise.then(() => {
128+
if (statusEl.textContent.startsWith("Loading")) {
129+
statusEl.textContent = "Python ready. Press Run.";
130+
}
131+
});
132+
}
133+
return pyodidePromise;
134+
}
135+
136+
runBtn.onclick = async () => {
137+
runBtn.disabled = true;
138+
statusEl.textContent = pyodidePromise ? "Running…" : statusEl.textContent;
139+
outEl.textContent = "";
140+
try {
141+
const py = await loadPython();
142+
py.setStdout({ batched: (s) => { outEl.textContent += s + "\n"; } });
143+
py.setStderr({ batched: (s) => { outEl.textContent += s + "\n"; } });
144+
await py.runPythonAsync(codeEl.value);
145+
statusEl.textContent = "Done. Edit the code and Run again.";
146+
} catch (err) {
147+
// Show a friendly Python-style traceback
148+
outEl.textContent += String(err);
149+
statusEl.textContent = "Error. Fix the code and press Run again.";
150+
}
151+
runBtn.disabled = false;
152+
};
153+
154+
resetBtn.onclick = () => { codeEl.value = starter; outEl.textContent = ""; };
155+
156+
// Tab key inserts spaces instead of leaving the editor
157+
codeEl.addEventListener("keydown", (e) => {
158+
if (e.key === "Tab") {
159+
e.preventDefault();
160+
const start = codeEl.selectionStart;
161+
codeEl.value = codeEl.value.slice(0, start) + " " + codeEl.value.slice(codeEl.selectionEnd);
162+
codeEl.selectionStart = codeEl.selectionEnd = start + 4;
163+
}
164+
if ((e.ctrlKey || e.metaKey) && e.key === "Enter") {
165+
e.preventDefault();
166+
runBtn.click();
167+
}
168+
});
169+
</script>
170+
</body>
171+
</html>
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
---
2+
title: 1. Variables and Types
3+
parent: Python Tutorials
4+
nav_order: 1
5+
---
6+
7+
# 1. Variables and Types
8+
9+
A variable stores a value under a name.
10+
11+
## Summary
12+
13+
```python
14+
fly_speed = 50 # int: whole number
15+
hood_angle = 35.5 # float: number with a decimal point
16+
is_intaking = False # bool: True or False
17+
name = 'Ctrl-Z' # str: text
18+
```
19+
20+
- `=` stores a value. `==` compares values (lesson 2).
21+
- Use `snake_case` for variable names. Use `UPPER_CASE` for constants, like in `const.py`.
22+
- Math: `+` `-` `*` `/`. Also useful: `//` divides and drops the remainder, `%` gives the remainder, `**` is power.
23+
- Useful functions: `abs(x)`, `min(a, b)`, `max(a, b)`.
24+
- An f-string puts values into text: `f'speed = {fly_speed}'`. Use `:.1f` to keep one decimal place: `f'{hood_angle:.1f}'`.
25+
26+
## In our robot code
27+
28+
Constants in `robot/const.py`:
29+
30+
```python
31+
SWERVE_DRIVE_GEAR_RATIO = 5.68
32+
DRIVETRAIN_TRACKWIDTH_METERS = inchesToMeters(23.5)
33+
```
34+
35+
Booleans in `robot/robot.py` store the state of the robot:
36+
37+
```python
38+
self.shoot_intent = False
39+
self.is_intaking = False
40+
self.fly_speed = 50
41+
```
42+
43+
## Try it
44+
45+
<iframe src="{{ '/assets/python-runner.html' | relative_url }}#b64:dGVhbSA9IDQwOTYKbmFtZSA9ICdDdHJsLVonCnNwZWVkID0gMy4yICAjIG1ldGVycyBwZXIgc2Vjb25kCnByaW50KGYnVGVhbSB7dGVhbX0gKHtuYW1lfSkgZHJpdmVzIGF0IHtzcGVlZH0gbS9zJyk=" width="100%" height="300px" style="border:1px solid #d1d5db;border-radius:8px;"></iframe>
46+
47+
## Exercises
48+
49+
### 1.1 Inches to meters
50+
51+
<iframe src="{{ '/assets/python-runner.html' | relative_url }}#b64:IyBUaGUgcm9ib3QgdXNlcyBtZXRlcnMuIFdlIGJ1aWxkIGluIGluY2hlcy4KIyAxIGluY2ggPSAwLjAyNTQgbWV0ZXJzCmluY2hlcyA9IDI4LjUgICMgZHJpdmUgYmFzZSB3aWR0aAoKIyBZT1VSIENPREUgSEVSRTogc2V0IG1ldGVycyB0byBpbmNoZXMgKiAwLjAyNTQKCgpwcmludChmJ3tpbmNoZXN9IGluY2hlcyA9IHttZXRlcnN9IG1ldGVycycp" width="100%" height="320px" style="border:1px solid #d1d5db;border-radius:8px;"></iframe>
52+
53+
<details markdown="block">
54+
<summary>Solution</summary>
55+
56+
```python
57+
meters = inches * 0.0254
58+
```
59+
</details>
60+
61+
### 1.2 Clamp a joystick value
62+
63+
<iframe src="{{ '/assets/python-runner.html' | relative_url }}#b64:c3RpY2sgPSAxLjQgICMgdGhlIGpveXN0aWNrIGNhbiByZXBvcnQgbW9yZSB0aGFuIDEuMAoKIyBZT1VSIENPREUgSEVSRTogY2xhbXAgc3RpY2sgaW50byBbLTEsIDFdLiBVc2UgbWluKCkgYW5kIG1heCgpLgojIFN0b3JlIHRoZSByZXN1bHQgaW4gY2xhbXBlZC4KCgpwcmludChmJ2NvbW1hbmRlZCBzcGVlZDoge2NsYW1wZWR9Jyk=" width="100%" height="320px" style="border:1px solid #d1d5db;border-radius:8px;"></iframe>
64+
65+
<details markdown="block">
66+
<summary>Solution</summary>
67+
68+
```python
69+
clamped = max(-1, min(1, stick))
70+
```
71+
72+
`min(1, stick)` sets the maximum. `max(-1, ...)` sets the minimum. Change `stick` to `-2.5` and run again.
73+
</details>
74+
75+
### 1.3 Battery flag
76+
77+
<iframe src="{{ '/assets/python-runner.html' | relative_url }}#b64:dm9sdGFnZSA9IDExLjgKCiMgWU9VUiBDT0RFIEhFUkU6IHNldCBpc19sb3cgdG8gVHJ1ZSB3aGVuIHZvbHRhZ2UgPCAxMi4wCgoKcHJpbnQoZidiYXR0ZXJ5OiB7dm9sdGFnZX0gViwgbG93ID0ge2lzX2xvd30nKQ==" width="100%" height="300px" style="border:1px solid #d1d5db;border-radius:8px;"></iframe>
78+
79+
<details markdown="block">
80+
<summary>Solution</summary>
81+
82+
```python
83+
is_low = voltage < 12.0
84+
```
85+
86+
A comparison is a value. It gives True or False, and you can store it in a variable.
87+
</details>
88+
89+
Next lesson: **2. Conditionals and Logic**.
Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
---
2+
title: 2. Conditionals and Logic
3+
parent: Python Tutorials
4+
nav_order: 2
5+
---
6+
7+
# 2. Conditionals and Logic
8+
9+
Do different things for different states.
10+
11+
## Summary
12+
13+
```python
14+
if voltage < 11:
15+
print('CRITICAL')
16+
elif voltage < 12:
17+
print('LOW')
18+
else:
19+
print('GOOD')
20+
```
21+
22+
- Indent with four spaces. The indented lines belong to the `if`.
23+
- The checks run from top to bottom. The first true condition wins.
24+
- Compare with: `==` (equal), `!=`, `<`, `<=`, `>`, `>=`.
25+
- Chain comparisons like math: `2.5 < time_left < 3`.
26+
- Combine conditions with `and`, `or`, `not`:
27+
28+
```python
29+
if is_intaking and fuel_in_hopper < 24:
30+
state = 'intaking'
31+
```
32+
33+
- `None` means: no value yet. Example: `self.auto_win = None` until the FMS sends the auto winner. Test it with `is None` or `is not None`, not with `==`.
34+
35+
> Common mistake: `if is_intaking = True:` assigns a value. It does not compare. Python shows a SyntaxError. Use `==` to compare.
36+
37+
## In our robot code
38+
39+
`robot/subsystems/intake.py`, `periodic()`. The order sets the priority:
40+
41+
```python
42+
if self.robot.intake_at_default:
43+
self.stop_intake()
44+
elif self.robot.clear_jam:
45+
self.set_intake_speed(-0.3 * 100)
46+
elif self.robot.is_intaking:
47+
self.set_intake_speed(0.85 * 100)
48+
```
49+
50+
`robot/robot.py`, the Auto Win logging:
51+
52+
```python
53+
if self.auto_win is None:
54+
SmartDashboard.putString("Auto Win", "UNKNOWN")
55+
```
56+
57+
## Try it
58+
59+
<iframe src="{{ '/assets/python-runner.html' | relative_url }}#b64:bWF0Y2hfdGltZSA9IDc1CgppZiBtYXRjaF90aW1lIDw9IDEwOgogICAgc2hpZnQgPSAnVFJBTlNJVElPTicKZWxpZiBtYXRjaF90aW1lIDw9IDExMDoKICAgIHNoaWZ0ID0gJ1NISUZUJwplbHNlOgogICAgc2hpZnQgPSAnRU5ER0FNRScKCnByaW50KGYndD17bWF0Y2hfdGltZX0sIHNoaWZ0ID0ge3NoaWZ0fScp" width="100%" height="320px" style="border:1px solid #d1d5db;border-radius:8px;"></iframe>
60+
61+
## Exercises
62+
63+
### 2.1 Battery warnings
64+
65+
<iframe src="{{ '/assets/python-runner.html' | relative_url }}#b64:dm9sdGFnZSA9IDEyLjEKCiMgWU9VUiBDT0RFIEhFUkU6CiMgcHJpbnQgQ1JJVElDQUwgaWYgdm9sdGFnZSA8IDExCiMgcHJpbnQgTE9XIGlmIHZvbHRhZ2UgPCAxMgojIGVsc2UgcHJpbnQgR09PRA==" width="100%" height="260px" style="border:1px solid #d1d5db;border-radius:8px;"></iframe>
66+
67+
<details markdown="block">
68+
<summary>Solution</summary>
69+
70+
```python
71+
if voltage < 11:
72+
print('CRITICAL')
73+
elif voltage < 12:
74+
print('LOW')
75+
else:
76+
print('GOOD')
77+
```
78+
</details>
79+
80+
### 2.2 The intake state machine
81+
82+
Fill in the state strings. Keep the branch order the same as `intake.py`.
83+
84+
<iframe src="{{ '/assets/python-runner.html' | relative_url }}#b64:aXNfaW50YWtpbmcgPSBGYWxzZQpjbGVhcl9qYW0gPSBUcnVlCmF0X2RlZmF1bHQgPSBGYWxzZQoKIyBLZWVwIHRoaXMgb3JkZXIgdGhlIHNhbWUgYXMgcGVyaW9kaWMoKSBpbiByb2JvdC9zdWJzeXN0ZW1zL2ludGFrZS5weS4KaWYgYXRfZGVmYXVsdDoKICAgIHN0YXRlID0gJycKZWxpZiBjbGVhcl9qYW06CiAgICBzdGF0ZSA9ICcnCmVsaWYgaXNfaW50YWtpbmc6CiAgICBzdGF0ZSA9ICcnCmVsc2U6CiAgICBzdGF0ZSA9ICcnCgpwcmludChmJ2ludGFrZSBpczoge3N0YXRlfScp" width="100%" height="420px" style="border:1px solid #d1d5db;border-radius:8px;"></iframe>
85+
86+
<details markdown="block">
87+
<summary>Solution</summary>
88+
89+
```python
90+
if at_default:
91+
state = 'stowed'
92+
elif clear_jam:
93+
state = 'reversing'
94+
elif is_intaking:
95+
state = 'intaking'
96+
else:
97+
state = 'stopped'
98+
```
99+
100+
Order matters. Two flags can be true at the same time, and the first matching `if` decides. Change the flags at the top and run again to see each branch.
101+
</details>
102+
103+
### 2.3 Who won auto?
104+
105+
<iframe src="{{ '/assets/python-runner.html' | relative_url }}#b64:YXV0b193aW4gPSBOb25lICAjIHdlIGRvIG5vdCBrbm93IHRoZSB3aW5uZXIgdW50aWwgdGhlIEZNUyBzZW5kcyBpdAoKIyBZT1VSIENPREUgSEVSRToKIyBwcmludCB1bmtub3duIGlmIGF1dG9fd2luIGlzIE5vbmUKIyBwcmludCBSRUQgaWYgYXV0b193aW4gaXMgVHJ1ZQojIHByaW50IEJMVUUgaWYgYXV0b193aW4gaXMgRmFsc2U=" width="100%" height="280px" style="border:1px solid #d1d5db;border-radius:8px;"></iframe>
106+
107+
<details markdown="block">
108+
<summary>Solution</summary>
109+
110+
```python
111+
if auto_win is None:
112+
print('unknown')
113+
elif auto_win:
114+
print('RED')
115+
else:
116+
print('BLUE')
117+
```
118+
119+
A bare `elif auto_win:` works because `auto_win` holds a bool. Set `auto_win = True` at the top and run again.
120+
</details>
121+
122+
Next lesson: **3. Lists and Loops**.

0 commit comments

Comments
 (0)