Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
5204 lines (4877 loc) · 214 KB
/
Copy pathapp.js
File metadata and controls
5204 lines (4877 loc) · 214 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Code Explorer browser application
*
* This module owns the visible application state and presentation logic. It
* initializes the editor, sends source code to the isolated Python worker,
* converts trace snapshots into beginner-friendly descriptions, and updates
* the workspace without a framework. Keeping these responsibilities in one
* module makes the MVP easy for a new contributor to follow from top to bottom.
*/
// The expanded curriculum lives in a dedicated data module so application
// controllers remain readable while the library grows to 134 programs.
import { ADDITIONAL_EXAMPLES } from "./curriculum.js?v=20260728-35";
// Both catalogs use one local-only matcher so metadata search behaves consistently.
import { catalogSearchText, matchesCatalogSearch } from "./catalog-search.js?v=20260728-35";
/**
* The initial program shown in the editor.
*
* It deliberately demonstrates assignment, a for loop, mutation through an
* augmented assignment, and console output so every major MVP panel has data.
*/
const DEFAULT_CODE = `total = 0
for number in range(1, 4):
total += number
print("Added", number)
print("Total:", total)`;
/**
* The browser-storage key used for the learner's latest Python source.
* A project-specific prefix prevents collisions with unrelated pages on the same origin.
*/
const SOURCE_STORAGE_KEY = "code-explorer-source";
/**
* Stores only the stable title of the reviewed example that originated the
* current study document. It never records progress, edits, or trace data.
*/
const SELECTED_EXAMPLE_STORAGE_KEY = "code-explorer-selected-example";
/**
* The browser-storage key for editor-only display preferences.
* Keeping it separate from source code lets either value evolve independently.
*/
const EDITOR_PREFERENCES_STORAGE_KEY = "code-explorer-editor-preferences";
/**
* The browser-storage key for independently remembered graph magnifications.
* A separate key keeps graph presentation unrelated to editor preferences.
*/
const GRAPH_ZOOM_STORAGE_KEY = "code-explorer-graph-zoom";
/** Browser storage key for learner-selected watch names and prepared stdin values. */
const LEARNING_PREFERENCES_STORAGE_KEY = "code-explorer-learning-preferences";
/**
* Safe defaults closely match the original editor presentation.
* Wrapping starts enabled for beginner-friendly viewing, and fourteen pixels
* preserves the previous visual size while remaining a clear numeric choice.
*/
const DEFAULT_EDITOR_PREFERENCES = Object.freeze({ wrap: true, fontSize: 14 });
/**
* Maximum wall-clock time allowed for one Python execution in the worker.
* Thirty seconds supports larger learning programs without leaving runaway code active indefinitely.
*/
const EXECUTION_TIMEOUT_MS = 30_000;
/**
* Reads the last saved program while safely handling browsers that block storage.
* The bundled starter remains the fallback for first visits and restricted environments.
* @returns {string} Saved Python source or the default learning example.
*/
function loadSavedCode() {
try {
return localStorage.getItem(SOURCE_STORAGE_KEY) ?? DEFAULT_CODE;
} catch (error) {
console.warn("Code Explorer could not read saved source.", error);
return DEFAULT_CODE;
}
}
/**
* Saves the current program after every edit so a page reload cannot erase it.
* Storage failures are non-fatal because the editor must remain usable in privacy modes.
* @param {string} code Complete Python source currently owned by the editor.
*/
function saveCode(code) {
try {
localStorage.setItem(SOURCE_STORAGE_KEY, code);
} catch (error) {
console.warn("Code Explorer could not save the current source.", error);
}
}
/**
* Restores validated editor display preferences from browser storage.
* Unknown font sizes are rejected so edited storage cannot produce an unusable editor.
* @returns {{wrap: boolean, fontSize: number}} Safe wrapping and font-size settings.
*/
function loadEditorPreferences() {
try {
// Parse the stored object only when the key exists.
const stored = JSON.parse(localStorage.getItem(EDITOR_PREFERENCES_STORAGE_KEY) || "null");
// The allowed list exactly mirrors the options presented in workspace.html.
const allowedFontSizes = [12, 14, 16, 18, 20, 22];
// Accept only an explicit boolean so strings such as "false" are not misread as true.
const wrap = typeof stored?.wrap === "boolean" ? stored.wrap : DEFAULT_EDITOR_PREFERENCES.wrap;
// Convert a valid stored number while falling back safely for missing or modified data.
const fontSize = allowedFontSizes.includes(Number(stored?.fontSize))
? Number(stored.fontSize)
: DEFAULT_EDITOR_PREFERENCES.fontSize;
return { wrap, fontSize };
} catch (error) {
// Storage or JSON failures must never prevent the editor from loading.
console.warn("Code Explorer could not read editor preferences.", error);
return { ...DEFAULT_EDITOR_PREFERENCES };
}
}
/**
* Persists the current editor presentation without touching the learner's code.
* Storage failures remain non-fatal for privacy-focused browser configurations.
*/
function saveEditorPreferences() {
try {
localStorage.setItem(EDITOR_PREFERENCES_STORAGE_KEY, JSON.stringify(state.editorPreferences));
} catch (error) {
console.warn("Code Explorer could not save editor preferences.", error);
}
}
/**
* Restores user-selected zoom percentages for both graph modes.
* Null means the graph should keep Cytoscape's automatic fitted scale until
* the learner deliberately uses a zoom control.
* @returns {{references: number|null, flow: number|null}} Valid saved percentages.
*/
function loadGraphZoomPreferences() {
try {
// Missing storage produces null so first-time graph layout remains content-aware.
const stored = JSON.parse(localStorage.getItem(GRAPH_ZOOM_STORAGE_KEY) || "null");
// Accept only finite percentages inside the same limits exposed by the sliders.
const validZoom = (value) => Number.isFinite(Number(value)) && Number(value) >= 40 && Number(value) <= 200
? Number(value)
: null;
return {
references: validZoom(stored?.references),
flow: validZoom(stored?.flow),
};
} catch (error) {
// Invalid JSON or restricted storage should never block graph rendering.
console.warn("Code Explorer could not read graph zoom preferences.", error);
return { references: null, flow: null };
}
}
/**
* Saves the two graph zoom percentages after an intentional zoom interaction.
* @param {{references: number|null, flow: number|null}} preferences Current graph zoom state.
*/
function saveGraphZoomPreferences(preferences) {
try {
localStorage.setItem(GRAPH_ZOOM_STORAGE_KEY, JSON.stringify(preferences));
} catch (error) {
console.warn("Code Explorer could not save graph zoom preferences.", error);
}
}
/**
* Restores the small pieces of learner-authored workspace state that remain useful across reloads.
* Trace bookmarks are intentionally excluded because they belong to one specific execution.
* @returns {{watches: string[], inputs: string}} Valid local learning preferences.
*/
function loadLearningPreferences() {
try {
const stored = JSON.parse(localStorage.getItem(LEARNING_PREFERENCES_STORAGE_KEY) || "null");
const watches = Array.isArray(stored?.watches)
? stored.watches.filter((name) => typeof name === "string" && /^[A-Za-z_]\w*$/.test(name)).slice(0, 12)
: [];
return { watches, inputs: typeof stored?.inputs === "string" ? stored.inputs : "" };
} catch (error) {
console.warn("Code Explorer could not read learning preferences.", error);
return { watches: [], inputs: "" };
}
}
/** Saves watches and prepared input without coupling them to the Python source document. */
function saveLearningPreferences() {
try {
localStorage.setItem(LEARNING_PREFERENCES_STORAGE_KEY, JSON.stringify({
watches: [...state.watches],
inputs: els.programInputs?.value || "",
}));
} catch (error) {
console.warn("Code Explorer could not save learning preferences.", error);
}
}
/**
* Prepares the sample responses bundled with an input-focused starter program.
* The value is written both to the open workspace and browser storage so a
* selection made on the landing page is ready after navigation.
* @param {string} inputs Newline-separated responses consumed by input().
*/
function prepareExampleInputs(inputs) {
if (els.programInputs) {
els.programInputs.value = inputs;
renderInputStatus();
}
try {
localStorage.setItem(LEARNING_PREFERENCES_STORAGE_KEY, JSON.stringify({
watches: [...state.watches],
inputs,
}));
} catch (error) {
console.warn("Code Explorer could not save the example inputs.", error);
}
}
/**
* Curated programs displayed by the Examples dialog.
*
* Each object contains presentation metadata plus the exact Python source to
* place in the editor. Keeping the examples as data avoids duplicating dialog
* markup and makes a new example a small, reviewable addition.
*/
const BASE_EXAMPLES = [
{
category: "Variables and Types",
topic: "Variables",
level: "Beginner",
title: "A tiny calculation",
description: "Watch names appear and values move through an expression.",
views: ["Story", "Before and After", "Variables"],
code: `price = 8
quantity = 3
total = price * quantity
print("Total:", total)`,
},
{
category: "Strings",
topic: "Strings",
level: "Beginner",
title: "Building a message",
description: "Combine text values and inspect the new string at each step.",
views: ["Story", "Before and After", "Structures"],
code: `language = "Python"
adjective = "visual"
message = language + " is " + adjective
print(message)`,
},
{
category: "Decisions",
topic: "Conditions",
level: "Beginner",
title: "Pass or try again",
description: "See which path Python chooses after checking a condition.",
views: ["Conditions", "Coverage", "Story"],
code: `score = 72
if score >= 50:
result = "Pass"
else:
result = "Try again"
print(result)`,
},
{
category: "Decisions",
topic: "Boolean logic",
level: "Developing",
title: "Checking multiple conditions",
description: "Break an and expression into the two facts Python checks.",
views: ["Conditions", "Before and After", "Coverage"],
code: `age = 20
has_ticket = True
if age >= 18 and has_ticket:
result = "Enter"
else:
result = "Wait"
print(result)`,
},
{
category: "Decisions",
topic: "Input and branches",
level: "Beginner",
title: "Different inputs, different paths",
description: "Change one prepared score and compare the branch and output.",
views: ["Input Playground", "Compare Runs", "Conditions"],
inputs: "72",
code: `score = int(input("Score: "))
if score >= 50:
message = "Pass"
else:
message = "Try again"
print(message)`,
},
{
category: "Loops",
topic: "For loop",
level: "Beginner",
title: "Running total",
description: "See an accumulator change during each loop iteration.",
views: ["Loop Table", "Loop Lab", "Coverage"],
code: DEFAULT_CODE,
},
{
category: "Loops",
topic: "While loop",
level: "Beginner",
title: "Countdown",
description: "Follow a condition and changing counter until the loop ends.",
views: ["Conditions", "Execution Path", "Loop Lab"],
code: `count = 3
while count > 0:
print(count)
count -= 1
print("Lift off!")`,
},
{
category: "Loops",
topic: "Break",
level: "Developing",
title: "Find the first match",
description: "Watch break end a search as soon as the target is found.",
views: ["Execution Path", "Coverage", "Loop Table"],
code: `numbers = [4, 7, 12, 15]
target = 12
found_at = -1
for index in range(len(numbers)):
if numbers[index] == target:
found_at = index
break
print("Found at:", found_at)`,
},
{
category: "Loops",
topic: "Continue",
level: "Developing",
title: "Skip unwanted values",
description: "See continue skip even values while the loop keeps moving.",
views: ["Execution Path", "Coverage", "Loop Table"],
code: `kept = []
for number in range(1, 7):
if number % 2 == 0:
continue
kept.append(number)
print(kept)`,
},
{
category: "Functions and Scope",
topic: "Functions",
level: "Beginner",
title: "A function call",
description: "Watch a local frame appear, calculate, and return a value.",
views: ["Function Journey", "Story", "Variables"],
code: `def double(number):
result = number * 2
return result
answer = double(4)
print(answer)`,
},
{
category: "Functions and Scope",
topic: "Nested calls",
level: "Developing",
title: "One function calling another",
description: "Follow two function frames as a value moves down and back up.",
views: ["Function Journey", "Story", "Variables"],
code: `def add_tax(price):
return price * 1.10
def final_price(price, discount):
reduced = price - discount
return add_tax(reduced)
total = final_price(50, 5)
print(round(total, 2))`,
},
{
category: "Collections",
topic: "Lists",
level: "Beginner",
title: "Growing a list",
description: "Observe a list as values are appended inside a loop.",
views: ["Structures", "Mutation Explorer", "Loop Table"],
code: `squares = []
for number in range(1, 4):
squares.append(number * number)
print(squares)`,
},
{
category: "References and Mutation",
topic: "Aliases",
level: "Developing",
title: "Two names sharing one list",
description: "See how mutation through one name appears through the other.",
views: ["References", "Mutation Explorer", "Variables"],
code: `first = [1, 2]
second = first
second.append(3)
print("first:", first)
print("second:", second)`,
},
{
category: "References and Mutation",
topic: "Object identity",
level: "Developing",
title: "Mutate or replace a list",
description: "Compare changing Object A with assigning a new Object B.",
views: ["Mutation Explorer", "References", "Before and After"],
code: `items = []
original = items
items.append("book")
items = ["new"]
print("original:", original)
print("items:", items)`,
},
{
category: "Collections",
topic: "Nested data",
level: "Developing",
title: "Nested student data",
description: "Open a dictionary containing a list and follow a nested update.",
views: ["Variables", "Structures", "References"],
code: `student = {
"name": "Aman",
"scores": [72, 84]
}
student["scores"].append(91)
average = sum(student["scores"]) / len(student["scores"])
print(student["name"], round(average, 1))`,
},
{
category: "Collections",
topic: "Dictionaries",
level: "Developing",
title: "Counting words",
description: "Watch dictionary keys appear and counts change inside a loop.",
views: ["Structures", "Mutation Explorer", "Loop Table"],
code: `words = ["code", "learn", "code", "trace"]
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts)`,
},
{
category: "Input, Errors and Debugging",
topic: "Input",
level: "Beginner",
title: "A personalized greeting",
description: "Prepare two input values and watch Python consume them in order.",
views: ["Input Playground", "Conditions", "Compare Runs"],
inputs: "Aman\n25",
code: `name = input("Your name: ")
age = int(input("Your age: "))
if age >= 18 and name:
message = "Welcome, " + name
else:
message = "Keep learning, " + name
print(message)`,
},
{
category: "Input, Errors and Debugging",
topic: "Errors",
level: "Beginner",
title: "An index to investigate",
description: "Stop at an IndexError and inspect the state that explains it.",
views: ["Error Coach", "Variables", "Structures"],
expectedError: "Intentional IndexError",
code: `colors = ["mint", "purple"]
requested_index = 2
print(colors[requested_index])`,
},
// These reviewed base lessons add value types, expressions, and two complete
// small programs. Their categories now place them beside matching v4 concepts.
{
category: "Variables and Types",
topic: "Numeric conversion",
level: "Beginner",
title: "Celsius to Fahrenheit",
description: "Follow arithmetic, a converted value, and a formatted result.",
views: ["Story", "Before and After", "Variables"],
code: `celsius = 24
factor = 9 / 5
fahrenheit = celsius * factor + 32
rounded = round(fahrenheit, 1)
print("Fahrenheit:", rounded)`,
},
{
category: "Operators and Expressions",
topic: "Number types",
level: "Developing",
title: "Division and remainders",
description: "Compare ordinary division, floor division, and modulo results.",
views: ["Variables", "Before and After", "Story"],
code: `minutes = 137
hours = minutes // 60
remaining_minutes = minutes % 60
decimal_hours = minutes / 60
print(hours, remaining_minutes, round(decimal_hours, 2))`,
},
{
category: "Strings",
topic: "String methods",
level: "Developing",
title: "Cleaning a username",
description: "Transform text step by step with strip, lower, and replace.",
views: ["Before and After", "Variables", "Story"],
code: `raw_name = " Ada Lovelace "
trimmed = raw_name.strip()
lowercase = trimmed.lower()
username = lowercase.replace(" ", "_")
length = len(username)
print(username)
print("Characters:", length)`,
},
{
category: "Variables and Types",
topic: "Boolean values",
level: "Beginner",
title: "Building status flags",
description: "Create Boolean facts and combine them into one readiness value.",
views: ["Variables", "Before and After", "Conditions"],
code: `has_name = True
has_email = True
accepted_rules = False
profile_ready = has_name and has_email and accepted_rules
print("Ready:", profile_ready)`,
},
{
category: "Guided Mini Programs",
topic: "First guided checkpoint",
level: "Guided Challenge",
title: "Smart Cafe Bill",
description: "Combine variables, arithmetic, a membership decision, tax, and a readable receipt.",
views: ["Story", "Before and After", "Conditions", "Variables"],
prerequisites: ["Variables", "Arithmetic operators", "Simple conditions", "print()"],
checkpointAfter: "Decisions",
code: `customer = "Maya"
drink_price = 4.50
pastry_price = 3.25
drink_count = 2
pastry_count = 1
is_member = True
drink_total = drink_price * drink_count
pastry_total = pastry_price * pastry_count
subtotal = drink_total + pastry_total
if is_member:
discount_rate = 0.10
else:
discount_rate = 0
discount = subtotal * discount_rate
discounted_total = subtotal - discount
tax = discounted_total * 0.13
final_total = discounted_total + tax
print("Cafe receipt for", customer)
print("Drinks:", round(drink_total, 2))
print("Pastries:", round(pastry_total, 2))
print("Member discount:", round(discount, 2))
print("Tax:", round(tax, 2))
print("Total:", round(final_total, 2))`,
},
{
category: "Variables and Types",
topic: "Mixed values",
level: "Guided Challenge",
title: "Personal profile summary",
description: "Combine text, numbers, conversion, and Boolean state in one report.",
views: ["Variables", "Story", "Before and After"],
code: `first_name = "Maya"
last_name = "Chen"
birth_year = 2002
current_year = 2026
favorite_language = "Python"
full_name = first_name + " " + last_name
age = current_year - birth_year
is_adult = age >= 18
headline = full_name + " learns " + favorite_language
print(headline)
print("Age:", age)
print("Adult:", is_adult)
print("Name length:", len(full_name))`,
},
// Decision examples cover elif, nesting, membership, and a complete quote so
// Conditions and Coverage can show more than one simple two-way branch.
{
category: "Decisions",
topic: "Elif ladder",
level: "Developing",
title: "Grade bands",
description: "See Python stop at the first matching branch in an elif ladder.",
views: ["Conditions", "Coverage", "Execution Path"],
code: `score = 84
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "Keep practicing"
print(grade)`,
},
{
category: "Decisions",
topic: "Nested conditions",
level: "Guided Challenge",
title: "Account access check",
description: "Follow an outer identity check and an inner permission decision.",
views: ["Conditions", "Coverage", "Execution Path"],
code: `username = "aman"
entered_password = "python123"
saved_password = "python123"
is_admin = False
account_active = True
if username and entered_password == saved_password:
if account_active:
if is_admin:
message = "Administrator access"
else:
message = "Standard access"
else:
message = "Account inactive"
else:
message = "Login failed"
print(message)`,
},
{
category: "Decisions",
topic: "Membership",
level: "Beginner",
title: "Allowed color check",
description: "Use in to test whether one value belongs to a collection.",
views: ["Conditions", "Structures", "Coverage"],
code: `allowed_colors = ["mint", "purple", "amber"]
selected_color = "purple"
if selected_color in allowed_colors:
message = "Color accepted"
else:
message = "Choose another color"
print(message)`,
},
{
category: "Decisions",
topic: "Business rules",
level: "Guided Challenge",
title: "Shipping quote",
description: "Combine membership, order value, distance, and several price paths.",
views: ["Conditions", "Coverage", "Before and After"],
code: `order_total = 72.50
distance_km = 18
is_member = True
remote_area = False
if order_total >= 100:
shipping = 0
elif is_member and order_total >= 50:
shipping = 4
else:
shipping = 8
if distance_km > 25:
shipping += 5
if remote_area:
shipping += 7
grand_total = order_total + shipping
print("Shipping:", shipping)
print("Grand total:", grand_total)`,
},
// Loop additions deliberately vary for, while, break, collections, nesting,
// and report-style programs so repeated execution becomes a full curriculum.
{
category: "Loops",
topic: "List building",
level: "Beginner",
title: "Even number squares",
description: "Build a new list from values that pass a condition inside a loop.",
views: ["Loop Table", "Mutation Explorer", "Conditions"],
code: `squares = []
for number in range(1, 7):
if number % 2 == 0:
squares.append(number * number)
print(squares)`,
},
{
category: "Loops",
topic: "Counting matches",
level: "Developing",
title: "Count passing scores",
description: "Watch a counter change only when an item meets the rule.",
views: ["Loop Table", "Conditions", "Watches"],
code: `scores = [42, 75, 88, 51, 39]
passing_count = 0
for score in scores:
if score >= 50:
passing_count += 1
print("Passing:", passing_count)`,
},
{
category: "Loops",
topic: "Running maximum",
level: "Developing",
title: "Find the highest temperature",
description: "Follow a candidate maximum as the loop inspects each value.",
views: ["Loop Table", "Before and After", "Conditions"],
code: `temperatures = [18, 23, 21, 27, 24]
highest = temperatures[0]
for temperature in temperatures:
if temperature > highest:
highest = temperature
print("Highest:", highest)`,
},
{
category: "Loops",
topic: "While target",
level: "Beginner",
title: "Save until the goal",
description: "Use while to repeat deposits until a changing total reaches its target.",
views: ["Loop Lab", "Loop Table", "Watches"],
code: `savings = 20
goal = 80
weekly_deposit = 15
while savings < goal:
savings += weekly_deposit
print("Saved:", savings)
print("Goal reached")`,
},
{
category: "Loops",
topic: "While mutation",
level: "Guided Challenge",
title: "Process a task queue",
description: "Remove tasks until a list is empty while recording completed work.",
views: ["Loop Lab", "Mutation Explorer", "Structures"],
code: `pending = ["email", "review", "deploy", "report"]
completed = []
step = 1
while pending:
current = pending.pop(0)
completed.append(current)
print("Step", step, current)
step += 1
remaining = len(pending)
finished = len(completed)
print("Remaining:", remaining)
print("Finished:", finished)
print("Completed tasks:", completed)`,
},
{
category: "Loops",
topic: "Nested loops",
level: "Guided Challenge",
title: "Build a session schedule",
description: "Follow an outer day loop and an inner session loop.",
views: ["Execution Path", "Loop Table", "Coverage"],
code: `days = ["Monday", "Tuesday"]
topics = ["Variables", "Loops", "Functions"]
schedule = []
session_number = 1
for day in days:
for topic in topics:
label = day + ": " + topic
schedule.append(label)
print(session_number, label)
session_number += 1
total_days = len(days)
total_sessions = len(schedule)
print("Days:", total_days)
print("Sessions:", total_sessions)`,
},
{
category: "Guided Mini Programs",
topic: "Loops checkpoint",
level: "Guided Challenge",
title: "Temperature Week Summary",
description: "Calculate a total, average, maximum, and warm-day count in one pass.",
views: ["Loop Table", "Watches", "Conditions"],
prerequisites: ["Lists", "For loops", "Running totals", "Conditions"],
checkpointAfter: "Loops",
code: `temperatures = [19, 23, 17, 26, 25, 21, 28]
total = 0
highest = temperatures[0]
warm_days = 0
for temperature in temperatures:
total += temperature
if temperature > highest:
highest = temperature
if temperature >= 25:
warm_days += 1
day_count = len(temperatures)
average = total / day_count
print("Days:", day_count)
print("Average:", round(average, 1))
print("Highest:", highest)
print("Warm days:", warm_days)`,
},
// Function additions move from simple arguments to scope, multiple returns,
// recursion, and a small pipeline that makes Function Journey especially useful.
{
category: "Functions and Scope",
topic: "Two parameters",
level: "Beginner",
title: "Calculate a rectangle",
description: "Follow two arguments into a function and one area value back out.",
views: ["Function Journey", "Variables", "Story"],
code: `def rectangle_area(width, height):
area = width * height
return area
result = rectangle_area(6, 4)
print("Area:", result)`,
},
{
category: "Functions and Scope",
topic: "Default parameter",
level: "Developing",
title: "Greeting with a default",
description: "Compare calls that use and replace a function's default argument.",
views: ["Function Journey", "Compare Runs", "Variables"],
code: `def greet(name, greeting="Hello"):
message = greeting + ", " + name
return message
first = greet("Sam")
second = greet("Mina", "Welcome")
print(first)
print(second)`,
},
{
category: "Functions and Scope",
topic: "Local and global scope",
level: "Developing",
title: "Same name, different scope",
description: "See a local variable temporarily hide a global name.",
views: ["Function Journey", "Variables", "Watches"],
code: `message = "Global message"
def create_message():
message = "Local message"
print("Inside:", message)
return message
returned = create_message()
print("Outside:", message)
print("Returned:", returned)`,
},
{
category: "Functions and Scope",
topic: "Multiple returns",
level: "Developing",
title: "Return minimum and maximum",
description: "Return two related values as a tuple and unpack them at the caller.",
views: ["Function Journey", "Structures", "Variables"],
code: `def find_limits(values):
smallest = min(values)
largest = max(values)
return smallest, largest
numbers = [8, 3, 12, 5]
low, high = find_limits(numbers)
print("Low:", low)
print("High:", high)`,
},
{
category: "Functions and Scope",
topic: "Recursion",
level: "Guided Challenge",
title: "Recursive factorial",
description: "Watch function frames grow and return through a small recursive calculation.",
views: ["Function Journey", "Story", "Variables"],
code: `def factorial(number):
if number <= 1:
return 1
smaller = factorial(number - 1)
return number * smaller
answer = factorial(4)
print("Factorial:", answer)`,
},
{
category: "Functions and Scope",
topic: "Function pipeline",
level: "Guided Challenge",
title: "Invoice calculation pipeline",
description: "Pass a value through subtotal, discount, tax, and formatting functions.",
views: ["Function Journey", "Before and After", "Variables"],
code: `def calculate_subtotal(price, quantity):
return price * quantity
def apply_discount(amount, rate):
discount = amount * rate
return amount - discount
def add_tax(amount, rate):
tax = amount * rate
return amount + tax
unit_price = 18.50
quantity = 3
subtotal = calculate_subtotal(unit_price, quantity)
discounted = apply_discount(subtotal, 0.10)
final_total = add_tax(discounted, 0.13)
print("Subtotal:", round(subtotal, 2))
print("Final:", round(final_total, 2))`,
},
// Collection additions give every major built-in container several concrete
// operations and include longer nested-data reports for Structures and Watches.
{
category: "Collections",
topic: "List indexes",
level: "Beginner",
title: "First, middle, and last",
description: "Read several list positions and compare positive and negative indexes.",
views: ["Structures", "Variables", "Story"],
code: `colors = ["red", "green", "blue", "purple"]
first = colors[0]
middle = colors[2]
last = colors[-1]
print(first, middle, last)`,
},
{
category: "Collections",
topic: "Tuple unpacking",
level: "Beginner",
title: "Unpack a coordinate",
description: "Split one fixed tuple into two named values.",
views: ["Structures", "Variables", "Before and After"],
code: `coordinate = (12, 7)
x, y = coordinate
distance_hint = x + y