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
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
# /// script
# requires-python = "==3.12"
# dependencies = [
#     "anywidget",
#     "marimo",
#     "marimo-learn==0.13.0",
# ]
# ///

"""
Example Marimo Notebook: Education Widgets Demo

This notebook demonstrates all formative assessment widgets.
Run with: marimo edit demo.py
"""

import marimo

__generated_with = "0.23.1"
app = marimo.App()


@app.cell
def _():
    import marimo as mo
    from marimo_learn import (
        ConceptMapWidget,
        FlashcardWidget,
        LabelingWidget,
        MatchingWidget,
        MultipleChoiceWidget,
        NumericEntryWidget,
        OrderingWidget,
        PredictThenCheckWidget,
    )

    return (
        ConceptMapWidget,
        FlashcardWidget,
        LabelingWidget,
        MatchingWidget,
        MultipleChoiceWidget,
        NumericEntryWidget,
        OrderingWidget,
        PredictThenCheckWidget,
        mo,
    )


@app.cell
def _(mo):
    mo.md("""
    # Formative Assessment Widgets

    This notebook demonstrates several widgets from the [marimo-learn](https://pypi.org/project/marimo-learn/) package that you can use to embed formative assessments in your lessons. They also show how easy it is to build custom plugins for the marimo notebook to meet your teaching needs.
    """)
    return


@app.cell
def _(mo):
    mo.md("""
    ## Concept Map
    """)
    return


@app.cell
def _(ConceptMapWidget, mo):
    concept_map = mo.ui.anywidget(
        ConceptMapWidget(
            question="Map the relationships between these Python concepts:",
            concepts=["function", "parameter", "argument", "return value", "call site"],
            terms=["defines", "accepts", "supplies", "produces", "invokes"],
            correct_edges=[
                {"from": "function", "to": "parameter", "label": "accepts"},
                {"from": "function", "to": "return value", "label": "produces"},
                {"from": "call site", "to": "argument", "label": "supplies"},
                {"from": "argument", "to": "parameter", "label": "defines"},
                {"from": "call site", "to": "function", "label": "invokes"},
            ],
        )
    )
    concept_map
    return (concept_map,)


@app.cell
def _(concept_map, mo):
    def concept_map_msg(widget):
        val = widget.value.get("value") or {}
        score = val.get("score")
        total = val.get("total", 5)
        if score is None:
            return "Draw connections between concepts to see your score."
        msg = f"**{score}/{total}** correct connection{'s' if total != 1 else ''}"
        if val.get("correct"):
            msg += " β€” complete!"
        return msg

    mo.md(concept_map_msg(concept_map))
    return


@app.cell
def _(mo):
    mo.md("""
    ## Flashcard Deck
    """)
    return


@app.cell
def _(FlashcardWidget, mo):
    flashcard_deck = mo.ui.anywidget(
        FlashcardWidget(
            question="Python Concepts β€” rate yourself on each card:",
            cards=[
                {
                    "front": "What does a list comprehension look like?",
                    "back": "[expr for item in iterable if condition] β€” e.g., [x**2 for x in range(10) if x % 2 == 0]",
                },
                {
                    "front": "What is the difference between a list and a tuple?",
                    "back": "Lists are mutable (can be changed after creation); tuples are immutable (cannot be changed).",
                },
                {
                    "front": "What does the `*args` parameter do in a function definition?",
                    "back": "It collects any number of positional arguments into a tuple named `args`.",
                },
                {
                    "front": "What is a Python generator?",
                    "back": "A function that uses `yield` to produce values one at a time, pausing between each, without building the full sequence in memory.",
                },
                {
                    "front": "What does `if __name__ == '__main__':` do?",
                    "back": "It runs the indented code only when the file is executed directly, not when it is imported as a module.",
                },
                {
                    "front": "What is the difference between `is` and `==` in Python?",
                    "back": "`==` tests value equality; `is` tests identity (whether two names refer to the exact same object in memory).",
                },
            ],
            shuffle=True,
        )
    )
    flashcard_deck
    return (flashcard_deck,)


@app.cell
def _(flashcard_deck, mo):
    def flashcard_progress(widget):
        val = widget.value.get("value") or {}
        results = val.get("results", {})
        counts = {"got_it": 0, "almost": 0, "no": 0}
        for r in results.values():
            counts[r["rating"]] = counts.get(r["rating"], 0) + 1
        return len(results), counts, val.get("complete", False)

    _rated, _counts, _complete = flashcard_progress(flashcard_deck)
    mo.md(f"""
    **Progress:** {_rated} card(s) rated β€”
    βœ“ Got it: {_counts["got_it"]}  
    ~ Almost: {_counts["almost"]}  
    βœ— No: {_counts["no"]}
    {"  πŸŽ‰ Deck complete!" if _complete else ""}
    """)
    return


@app.cell
def _(mo):
    mo.md("""
    ## Labeling Question
    """)
    return


@app.cell
def _(LabelingWidget, mo):
    labeling_question = mo.ui.anywidget(
        LabelingWidget(
            question="Label the parts of this Python code:",
            labels=[
                "Variable declaration",
                "Function call",
                "String literal",
                "Arithmetic operation",
            ],
            text_lines=[
                "name = 'Alice'",
                "age = 25",
                "result = age + 5",
                "print(name)",
            ],
            correct_labels={
                0: [0, 2],  # Line 0: labels 0 and 2
                1: [0],  # Line 1: label 0
                2: [0, 3],  # Line 2: labels 0 and 3
                3: [1],  # Line 3: label 1
            },
        )
    )
    labeling_question
    return (labeling_question,)


@app.cell
def _(labeling_question, mo):
    _val = labeling_question.value.get("value") or {}
    _total = _val.get("total", 0)
    _msg = f"Score: {_val['score']}/{_total}" if _total > 0 else "Not submitted yet"
    mo.md(f"**{_msg}**")
    return


@app.cell
def _(mo):
    mo.md("""
    ## Matching Question
    """)
    return


@app.cell
def _(MatchingWidget, mo):
    matching_question = mo.ui.anywidget(
        MatchingWidget(
            question="Match the programming languages to their primary paradigms:",
            left=["Python", "Haskell", "C", "SQL"],
            right=["Functional", "Procedural", "Multi-paradigm", "Declarative"],
            correct_matches={0: 2, 1: 0, 2: 1, 3: 3},
        )
    )
    matching_question
    return (matching_question,)


@app.cell
def _(matching_question, mo):
    _val = matching_question.value.get("value") or {}
    _msg = f"Score: {_val['score']}/{_val['total']}" if _val else "Not answered yet"
    mo.md(f"**{_msg}**")
    return


@app.cell
def _(mo):
    mo.md("""
    ## Multiple Choice Question
    """)
    return


@app.cell
def _(MultipleChoiceWidget, mo):
    multiple_choice_question = mo.ui.anywidget(
        MultipleChoiceWidget(
            question="What is the capital of France?",
            options=["London", "Berlin", "Paris", "Madrid"],
            correct_answer=2,
            explanation="Paris has been the capital of France since the 12th century.",
        )
    )
    multiple_choice_question
    return (multiple_choice_question,)


@app.cell
def _(mo, multiple_choice_question):
    _val = multiple_choice_question.value.get("value") or {}
    if _val.get("answered"):
        _msg = "Score: 1/1" if _val.get("correct") else "Score: 0/1"
    else:
        _msg = "Not answered yet"
    mo.md(f"**{_msg}**")
    return


@app.cell
def _(mo):
    mo.md("""
    ## Ordering Question
    """)
    return


@app.cell
def _(OrderingWidget, mo):
    ordering_question = mo.ui.anywidget(
        OrderingWidget(
            question="Arrange these steps of the scientific method in the correct order:",
            items=[
                "Ask a question",
                "Do background research",
                "Construct a hypothesis",
                "Test with an experiment",
                "Analyze data",
                "Draw conclusions",
            ],
            shuffle=True,
        )
    )
    ordering_question
    return (ordering_question,)


@app.cell
def _(mo, ordering_question):
    _val = ordering_question.value.get("value") or {}
    if _val.get("correct") is not None and _val.get("order"):
        _msg = "Score: 1/1" if _val.get("correct") else "Score: 0/1"
    else:
        _msg = "Not answered yet"
    mo.md(f"**{_msg}**")
    return


@app.cell
def _(mo):
    mo.md("""
    ## Numeric Entry Question
    """)
    return


@app.cell
def _(NumericEntryWidget, mo):
    numeric_entry_question = mo.ui.anywidget(
        NumericEntryWidget(
            question="How many bits are in one byte?",
            correct_answer=8,
            tolerance=0.5,
            explanation="A byte consists of exactly 8 bits.",
        )
    )
    numeric_entry_question
    return (numeric_entry_question,)


@app.cell
def _(mo, numeric_entry_question):
    _val = numeric_entry_question.value.get("value") or {}
    if _val.get("answered"):
        _msg = "Score: 1/1" if _val.get("ok") else "Score: 0/1"
    else:
        _msg = "Not answered yet"
    mo.md(f"**{_msg}**")
    return


@app.cell
def _(mo):
    mo.md("""
    ## Predict-Then-Check Question
    """)
    return


@app.cell
def _(PredictThenCheckWidget, mo):
    predict_then_check_question = mo.ui.anywidget(
        PredictThenCheckWidget(
            question="What does this Python code print?",
            code='words = ["one", "two", "three"]\nprint(len(words))',
            output="3",
            options=["2", "3", "['one', 'two', 'three']", "None"],
            correct_answer=1,
            explanations=[
                "Wrong: len() counts all items; the list has three elements.",
                "Correct: len() returns the number of items, which is 3.",
                "Wrong: len() returns an integer count, not the list itself.",
                "Wrong: len() always returns an integer, never None.",
            ],
        )
    )
    predict_then_check_question
    return (predict_then_check_question,)


@app.cell
def _(mo, predict_then_check_question):
    _val = predict_then_check_question.value.get("value") or {}
    if _val.get("answered"):
        _msg = "Score: 1/1" if _val.get("correct") else "Score: 0/1"
    else:
        _msg = "Not answered yet"
    mo.md(f"**{_msg}**")
    return


@app.cell
def _(mo):
    mo.md("""
    ---

    ## Quiz Results Summary

    You can access the values from all widgets to create a summary or scoring system.
    """)
    return


@app.cell
def _(
    concept_map,
    flashcard_deck,
    matching_question,
    mo,
    multiple_choice_question,
    numeric_entry_question,
    ordering_question,
    predict_then_check_question,
):
    def widget_val(widget):
        return widget.value.get("value") or {}

    def calculate_score():
        score = 0
        total = 0
        for val, answered_key, correct_key in [
            (widget_val(concept_map), "score", "correct"),
            (widget_val(matching_question), "score", "correct"),
            (widget_val(multiple_choice_question), "answered", "correct"),
            (widget_val(ordering_question), "order", "correct"),
            (widget_val(numeric_entry_question), "answered", "ok"),
            (widget_val(predict_then_check_question), "answered", "correct"),
        ]:
            if val.get(answered_key) is not None and val.get(answered_key) is not False:
                total += 1
                if val.get(correct_key):
                    score += 1
        fc = widget_val(flashcard_deck)
        if fc.get("results"):
            total += 1
            if fc.get("complete"):
                score += 1
        return score, total

    score, total = calculate_score()
    mo.md(f"""
    ### Current Score: {score}/{total}

    {"πŸŽ‰ Perfect score!" if score == total and total > 0 else "Keep going!" if total > 0 else "Answer the questions above to see your score."}
    """)
    return


if __name__ == "__main__":
    app.run()