Add levels 08-12 (functions, dicts, files, libraries, errors), persistent data/ folder, narration

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
denis
2026-10-16 17:04:09 +02:00
parent 88879ce8fb
commit b19d3c038d
55 changed files with 1337 additions and 11 deletions
+9 -2
View File
@@ -63,6 +63,9 @@ Flux de contribution documenté (`CONTRIBUTING.md`, `docs/MAINTAINERS.md`, `docs
- Synchronisation : jeton aléatoire côté client, sans compte ; fusion côté client
(`ProgressStore.import`, mode `merge`).
- Licence **MIT** (« PyQuest contributors ») — choisie par défaut, modifiable.
- **Fichiers dans Pyodide** : seul le dossier `data/` (monté sur IndexedDB via IDBFS dans le worker) survit
au rechargement ; le reste du système de fichiers est en mémoire. Le niveau 10 l'enseigne. Les tests sous
Node n'ont pas IndexedDB : `data/` y est un dossier mémoire (suffisant pour valider les solutions).
- Langue des commits/identifiants : anglais ; commentaires : français ; 4 espaces.
## À faire — priorités pour la prochaine session
@@ -104,8 +107,12 @@ Flux de contribution documenté (`CONTRIBUTING.md`, `docs/MAINTAINERS.md`, `docs
badges illustrés, feedback coloré (vert/rouge, toujours doublé d'un texte). Procéder en 3
temps avec validation à chaque étape (propositions → CSS/éditeur → carte + personnage).
3. **Niveaux 08 à 14** (tableau dans `docs/design/05-curriculum.md`). Méthode : écrire le YAML
(fr + en obligatoires), `make validate-levels`, ajouter au manifeste, parcours e2e. Niveaux **00 à 07 faits**
(cœur impératif). Prochain : **08 Découper en fonctions** (après la phase de design, voir 2).
(fr + en obligatoires), `make validate-levels`, ajouter au manifeste, parcours e2e. Niveaux **00 à 12 faits**
(cœur impératif + structuration + robustesse), solutions vérifiées par `make test`, narration générée.
Prochain : **13 et 14** (POO + dessin) : ils exigent une **fonctionnalité de moteur nouvelle**, un canvas de
dessin façon `turtle` (module Python `pyquest` ou similaire qui poste des commandes de dessin du worker
vers un canvas de l'interface, + un kind de test déclaratif pour valider le dessin). À concevoir avec
l'utilisateur avant de coder. Voir aussi 05-curriculum.md (13 `Crayon`, 14 motifs sauvegardés).
3. **Navigateurs** : validé dans Chromium 155 seulement. Reste Firefox, Safari desktop et surtout
**iOS Safari** (mémoire WASM, autoplay audio, `SharedArrayBuffer` + `Atomics.wait`).
4. Icônes PNG (iOS) en plus de `app/icons/icon.svg`.
+31
View File
@@ -19,6 +19,9 @@
// Saisie (input) : le worker est bloqué dans Python pendant input(), il ne peut donc pas lire de
// message. Le client répond via un SharedArrayBuffer : Int32[0] = état (0 attente, 1 réponse,
// 2 fin de saisie/EOF), Int32[1] = longueur en octets, puis le texte UTF-8 à partir de l'octet 8.
// Dossier de sauvegarde de l'apprenant (relatif au dossier de travail de Python) : persiste d'une session à
// l'autre grâce à IndexedDB (IDBFS). Le reste du système de fichiers est en mémoire et disparaît au rechargement.
const DATA_DIR = '/home/pyodide/data';
const SIGINT = 2;
const INPUT_WAIT_SLICE_MS = 50;
const INPUT_HEADER_BYTES = 8;
@@ -28,6 +31,7 @@ class PythonWorker {
#pyodide = null;
#runner = null;
#interruptView = null;
#persistent = false; // vrai si data/ est monté sur IndexedDB
#inputControl = null;
#inputData = null;
#currentId = null;
@@ -69,6 +73,7 @@ class PythonWorker {
this.#pyodide.FS.writeFile('/pyquest/pyquest_runner.py', source);
this.#pyodide.runPython("import sys; sys.path.insert(0, '/pyquest')");
this.#runner = this.#pyodide.pyimport('pyquest_runner');
await this.#mountDataDir();
// Sans SharedArrayBuffer, pas de saisie : input() lève EOFError (comportement par défaut).
if (inputBuffer instanceof SharedArrayBuffer) {
@@ -104,6 +109,28 @@ class PythonWorker {
#decoders = { stdout: new TextDecoder(), stderr: new TextDecoder() };
/** Crée data/ et, si IndexedDB est disponible, le monte pour que son contenu survive aux sessions. */
async #mountDataDir() {
const { FS } = this.#pyodide;
FS.mkdirTree(DATA_DIR);
// Hors navigateur (tests sous Node) ou si IndexedDB est refusé : data/ reste un dossier en mémoire.
if (typeof indexedDB === 'undefined' || !FS.filesystems?.IDBFS) {
return;
}
try {
FS.mount(FS.filesystems.IDBFS, {}, DATA_DIR);
await this.#syncFs(true); // charge le contenu déjà sauvegardé
this.#persistent = true;
} catch {
this.#persistent = false;
}
}
/** Synchronise data/ avec IndexedDB (populate = true : IndexedDB → mémoire ; false : mémoire → IndexedDB). */
#syncFs(populate) {
return new Promise((resolve, reject) => this.#pyodide.FS.syncfs(populate, (error) => (error ? reject(error) : resolve())));
}
/** Bloque jusqu'à la réponse de l'apprenant. Renvoie le JSON attendu par pyquest_runner. */
#requestInput(prompt) {
const control = this.#inputControl;
@@ -143,6 +170,10 @@ class PythonWorker {
}
try {
const raw = this.#runner.run_cell(code, JSON.stringify(collect), isolated);
// Les fichiers écrits dans data/ sont sauvegardés avant de rendre la main (un rechargement immédiat les garde).
if (this.#persistent) {
await this.#syncFs(false).catch(() => {});
}
self.postMessage({ type: 'result', id, ...JSON.parse(raw) });
} catch (error) {
// Erreur hors du code de l'apprenant (bug du runner ou de Pyodide).
+2 -1
View File
@@ -30,4 +30,5 @@ Les missions nommées dans le brief sont toutes couvertes : calculatrice de pour
jeu du nombre mystère (05, 07), générateur de mots de passe (06, 11), mini-agenda (08–10), jeu de
dessin (13–14).
**Les 3 premiers niveaux à coder en priorité (point 7 du brief) sont 00, 01, 02** — cf. `CONTEXT.md`.
**État** : niveaux 00 à 12 écrits (voir `levels/`). Les niveaux 13 et 14 (POO et dessin) attendent un canvas de
dessin dans le moteur — cf. `CONTEXT.md`. Le niveau 10 s'appuie sur le dossier persistant `data/` (IDBFS).
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+38
View File
@@ -0,0 +1,38 @@
{
"en": {
"03f71e2631d3e61f": {
"text": "For the mission, a list can receive an item with append: agenda.append(\"Dentist\"). A function that receives a list can therefore change it. And nothing stops a function from being short: a good name matters as much as the code.",
"voice": "en_US-ljspeech-high"
},
"1f039a619dbd29bb": {
"text": "A function stores instructions under a name. We define it with def, then call it by writing its name followed by parentheses. Written once, it can be used as many times as we like.",
"voice": "en_US-ljspeech-high"
},
"ead7428ab51d88f0": {
"text": "A function can also give back a result with return. Careful: print shows on screen, but only return gives a value we can store in a variable: total = add(2, 3).",
"voice": "en_US-ljspeech-high"
},
"ef0de72707e53fd9": {
"text": "A function can receive values, called parameters: def greet(name):. When we call it, we give the value in parentheses: greet(\"Alice\"). The parameter name is then \"Alice\" inside the function.",
"voice": "en_US-ljspeech-high"
}
},
"fr": {
"48ad607f6b05f823": {
"text": "Une fonction range des instructions sous un nom. On la définit avec def, puis on l'appelle en écrivant son nom suivi de parenthèses. Écrite une fois, elle peut servir autant de fois qu'on veut.",
"voice": "fr_FR-siwis-medium"
},
"a52eb6308b40dbaa": {
"text": "Pour la mission, une liste peut recevoir un élément avec append : agenda.append(\"Dentiste\"). Une fonction qui reçoit une liste peut donc la modifier. Et rien n'empêche une fonction de s'écrire en deux lignes : un bon nom compte autant que le code.",
"voice": "fr_FR-siwis-medium"
},
"b6ec691e41a479a1": {
"text": "Une fonction peut aussi renvoyer un résultat avec return. Attention : print affiche à l'écran, mais seul return donne une valeur qu'on peut ranger dans une variable : total = add(2, 3).",
"voice": "fr_FR-siwis-medium"
},
"d9c2391bdef4fd14": {
"text": "Une fonction peut recevoir des valeurs, appelées paramètres : def greet(name):. Quand on l'appelle, on donne la valeur entre parenthèses : greet(\"Alice\"). Le paramètre name vaut alors \"Alice\" dans la fonction.",
"voice": "fr_FR-siwis-medium"
}
}
}
+204
View File
@@ -0,0 +1,204 @@
id: 08-functions
title:
fr: Découper en fonctions
en: Splitting into functions
difficulty: 3
xp: 80
requires:
- 07-while
steps:
- type: explain
voice: true
text:
fr: "Une fonction range des instructions sous un nom. On la définit avec `def`, puis on l'appelle en écrivant son nom suivi de parenthèses. Écrite une fois, elle peut servir autant de fois qu'on veut."
en: "A function stores instructions under a name. We define it with `def`, then call it by writing its name followed by parentheses. Written once, it can be used as many times as we like."
- type: code
starter: |
def greet():
print("Bonjour !")
greet()
instruction:
fr: Appelle la fonction `greet()` deux fois pour afficher deux fois Bonjour !
en: Call the `greet()` function twice to show Bonjour ! twice.
tests:
- kind: stdout_equals
value: "Bonjour !\nBonjour !\n"
hints:
fr:
- "Écris `greet()` une deuxième fois, sur une nouvelle ligne, sans décalage."
en:
- "Write `greet()` a second time, on a new line, without indentation."
solution: |
def greet():
print("Bonjour !")
greet()
greet()
- type: explain
voice: true
text:
fr: "Une fonction peut recevoir des valeurs, appelées paramètres : `def greet(name):`. Quand on l'appelle, on donne la valeur entre parenthèses : `greet(\"Alice\")`. Le paramètre `name` vaut alors \"Alice\" dans la fonction."
en: "A function can receive values, called parameters: `def greet(name):`. When we call it, we give the value in parentheses: `greet(\"Alice\")`. The parameter `name` is then \"Alice\" inside the function."
- type: code
starter: |
def greet(name):
print("Bonjour", name)
greet("Alice")
instruction:
fr: Appelle `greet()` avec Alice, puis avec Bob, pour afficher une ligne par prénom.
en: Call `greet()` with Alice, then with Bob, to show one line per name.
tests:
- kind: stdout_equals
value: "Bonjour Alice\nBonjour Bob\n"
hints:
fr:
- "Ajoute un deuxième appel avec \"Bob\" entre les parenthèses."
en:
- "Add a second call with \"Bob\" between the parentheses."
solution: |
def greet(name):
print("Bonjour", name)
greet("Alice")
greet("Bob")
- type: explain
voice: true
text:
fr: "Une fonction peut aussi renvoyer un résultat avec `return`. Attention : `print` affiche à l'écran, mais seul `return` donne une valeur qu'on peut ranger dans une variable : `total = add(2, 3)`."
en: "A function can also give back a result with `return`. Careful: `print` shows on screen, but only `return` gives a value we can store in a variable: `total = add(2, 3)`."
- type: code
starter: |
def add(a, b):
print(a + b)
total = add(2, 3)
print(total)
instruction:
fr: "Ici `total` vaut None car `add()` affiche au lieu de renvoyer. Utilise `return` pour que `total` vaille 5."
en: "Here `total` is None because `add()` prints instead of returning. Use `return` so that `total` is 5."
tests:
- kind: var_equals
name: total
value: 5
- kind: stdout_equals
value: "5\n"
hints:
fr:
- "Dans la fonction, remplace `print(a + b)` par `return a + b`."
en:
- "In the function, replace `print(a + b)` with `return a + b`."
solution: |
def add(a, b):
return a + b
total = add(2, 3)
print(total)
- type: code
starter: |
def square(n):
pass
number = int(input("Un nombre ? "))
print(square(number))
instruction:
fr: Complète `square(n)` pour qu'elle renvoie le carré de `n` (4 donne 16, 7 donne 49).
en: Complete `square(n)` so that it returns the square of `n` (4 gives 16, 7 gives 49).
tests:
- kind: stdout_matches_regex
value: "^[^\\n]*16\\n$"
inputs:
- "4"
message:
fr: "Avec 4, il faut afficher 16."
en: "With 4, it must show 16."
- kind: stdout_matches_regex
value: "^[^\\n]*49\\n$"
inputs:
- "7"
message:
fr: "Avec 7, il faut afficher 49."
en: "With 7, it must show 49."
- kind: code_contains
value: return
message:
fr: La fonction doit utiliser return.
en: The function must use return.
hints:
fr:
- "Le carré de n, c'est n multiplié par n."
- "Remplace `pass` par `return n * n`."
en:
- "The square of n is n multiplied by n."
- "Replace `pass` with `return n * n`."
solution: |
def square(n):
return n * n
number = int(input("Un nombre ? "))
print(square(number))
- type: explain
voice: true
text:
fr: "Pour la mission, une liste peut recevoir un élément avec `append` : `agenda.append(\"Dentiste\")`. Une fonction qui reçoit une liste peut donc la modifier. Et rien n'empêche une fonction de s'écrire en deux lignes : un bon nom compte autant que le code."
en: "For the mission, a list can receive an item with `append`: `agenda.append(\"Dentist\")`. A function that receives a list can therefore change it. And nothing stops a function from being short: a good name matters as much as the code."
mission:
title:
fr: Mini-agenda, version 1
en: Mini agenda, version 1
goal:
fr: "Écris `add_appointment(agenda, text)` qui ajoute un rendez-vous à la liste, et `show_agenda(agenda)` qui affiche chaque rendez-vous sur une ligne, sous la forme « - rendez-vous »."
en: "Write `add_appointment(agenda, text)` that adds an appointment to the list, and `show_agenda(agenda)` that shows each appointment on one line, as \"- appointment\"."
starter: |
agenda = []
def add_appointment(agenda, text):
# Ajoute text à la liste agenda
pass
def show_agenda(agenda):
# Affiche chaque rendez-vous sur une ligne : "- <rendez-vous>"
pass
add_appointment(agenda, input("Premier rendez-vous ? "))
add_appointment(agenda, input("Deuxième rendez-vous ? "))
show_agenda(agenda)
tests:
- kind: stdout_matches_regex
value: "^[^\\n]*- Dentiste 10h\\n- Cinéma 20h\\n$"
inputs:
- Dentiste 10h
- Cinéma 20h
message:
fr: "Avec « Dentiste 10h » puis « Cinéma 20h », il faut afficher deux lignes : - Dentiste 10h puis - Cinéma 20h."
en: "With \"Dentiste 10h\" then \"Cinéma 20h\", it must show two lines: - Dentiste 10h then - Cinéma 20h."
- kind: stdout_matches_regex
value: "^[^\\n]*- Yoga\\n- Marché\\n$"
inputs:
- Yoga
- Marché
- kind: code_contains
value: def add_appointment
message:
fr: Définis la fonction add_appointment.
en: Define the add_appointment function.
- kind: code_contains
value: def show_agenda
message:
fr: Définis la fonction show_agenda.
en: Define the show_agenda function.
solution: |
agenda = []
def add_appointment(agenda, text):
agenda.append(text)
def show_agenda(agenda):
for appointment in agenda:
print("-", appointment)
add_appointment(agenda, input("Premier rendez-vous ? "))
add_appointment(agenda, input("Deuxième rendez-vous ? "))
show_agenda(agenda)
reward_sound: success_small
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+38
View File
@@ -0,0 +1,38 @@
{
"en": {
"194cbc856adc7b66": {
"text": "We add or change a value by assigning it to its key: person[\"city\"] = \"Lyon\". To test that a key exists, we write \"city\" in person.",
"voice": "en_US-ljspeech-high"
},
"2929b052778dc2ce": {
"text": "A dictionary stores values labelled by keys, between curly braces: person = {\"name\": \"Alice\", \"age\": 30}. We read a value with its key: person[\"name\"] is \"Alice\".",
"voice": "en_US-ljspeech-high"
},
"71f943a3c23717e7": {
"text": "To search, we go through the list and keep the items that match. \"ne\" in \"Cinéma\" is True if the text contains those letters. We put the items found in a new list, which the function returns.",
"voice": "en_US-ljspeech-high"
},
"b5064341e6e80bce": {
"text": "A list can contain dictionaries: this is how we represent several items that each have several pieces of information, like appointments. We go through them with for, and each item is a dictionary.",
"voice": "en_US-ljspeech-high"
}
},
"fr": {
"2777d138555c3364": {
"text": "Une liste peut contenir des dictionnaires : c'est ainsi qu'on représente plusieurs éléments qui ont chacun plusieurs informations, comme des rendez-vous. On les parcourt avec for, et chaque élément est un dictionnaire.",
"voice": "fr_FR-siwis-medium"
},
"3f651fd011a8ad28": {
"text": "Pour chercher, on parcourt la liste et on garde les éléments qui conviennent. \"ne\" in \"Cinéma\" vaut True si le texte contient ces lettres. On range les éléments trouvés dans une nouvelle liste, que la fonction renvoie.",
"voice": "fr_FR-siwis-medium"
},
"76260487fed47abc": {
"text": "Un dictionnaire range des valeurs étiquetées par des clés, entre accolades : person = {\"name\": \"Alice\", \"age\": 30}. On lit une valeur avec sa clé : person[\"name\"] vaut \"Alice\".",
"voice": "fr_FR-siwis-medium"
},
"f908dede13643d48": {
"text": "On ajoute ou on change une valeur en l'affectant à sa clé : person[\"city\"] = \"Lyon\". Pour tester qu'une clé existe, on écrit \"city\" in person.",
"voice": "fr_FR-siwis-medium"
}
}
}
+242
View File
@@ -0,0 +1,242 @@
id: 09-dicts
title:
fr: Structurer les données
en: Structuring data
difficulty: 3
xp: 90
requires:
- 08-functions
steps:
- type: explain
voice: true
text:
fr: "Un dictionnaire range des valeurs étiquetées par des clés, entre accolades : `person = {\"name\": \"Alice\", \"age\": 30}`. On lit une valeur avec sa clé : `person[\"name\"]` vaut \"Alice\"."
en: "A dictionary stores values labelled by keys, between curly braces: `person = {\"name\": \"Alice\", \"age\": 30}`. We read a value with its key: `person[\"name\"]` is \"Alice\"."
- type: code
starter: |
person = {"name": "Alice", "age": 30}
print(person["name"])
instruction:
fr: "Affiche la phrase Alice a 30 ans en utilisant les deux clés du dictionnaire."
en: "Show the sentence Alice a 30 ans using both keys of the dictionary."
tests:
- kind: stdout_equals
value: "Alice a 30 ans\n"
- kind: code_contains
value: person["age"]
message:
fr: Lis l'âge avec person["age"] au lieu de l'écrire à la main.
en: Read the age with person["age"] instead of typing it by hand.
hints:
fr:
- "Mets plusieurs valeurs dans `print`, séparées par des virgules."
- "`print(person[\"name\"], \"a\", person[\"age\"], \"ans\")`"
en:
- "Put several values in `print`, separated by commas."
- "`print(person[\"name\"], \"a\", person[\"age\"], \"ans\")`"
solution: |
person = {"name": "Alice", "age": 30}
print(person["name"], "a", person["age"], "ans")
- type: explain
voice: true
text:
fr: "On ajoute ou on change une valeur en l'affectant à sa clé : `person[\"city\"] = \"Lyon\"`. Pour tester qu'une clé existe, on écrit `\"city\" in person`."
en: "We add or change a value by assigning it to its key: `person[\"city\"] = \"Lyon\"`. To test that a key exists, we write `\"city\" in person`."
- type: code
starter: |
person = {"name": "Alice"}
print(person["name"])
instruction:
fr: Ajoute la clé city avec la valeur Lyon au dictionnaire, puis affiche la ville.
en: Add the key city with the value Lyon to the dictionary, then show the city.
tests:
- kind: stdout_equals
value: "Lyon\n"
hints:
fr:
- "Une ligne pour ajouter la clé, une autre pour l'afficher."
- "`person[\"city\"] = \"Lyon\"` puis `print(person[\"city\"])`."
en:
- "One line to add the key, another to show it."
- "`person[\"city\"] = \"Lyon\"` then `print(person[\"city\"])`."
solution: |
person = {"name": "Alice"}
person["city"] = "Lyon"
print(person["city"])
- type: explain
voice: true
text:
fr: "Une liste peut contenir des dictionnaires : c'est ainsi qu'on représente plusieurs éléments qui ont chacun plusieurs informations, comme des rendez-vous. On les parcourt avec `for`, et chaque élément est un dictionnaire."
en: "A list can contain dictionaries: this is how we represent several items that each have several pieces of information, like appointments. We go through them with `for`, and each item is a dictionary."
- type: code
starter: |
agenda = [
{"time": "10h", "title": "Dentiste"},
{"time": "20h", "title": "Cinéma"},
]
for item in agenda:
print(item)
instruction:
fr: "Change le `print` pour afficher une ligne par rendez-vous sous la forme 10h - Dentiste."
en: "Change the `print` to show one line per appointment, as 10h - Dentiste."
tests:
- kind: stdout_equals
value: "10h - Dentiste\n20h - Cinéma\n"
hints:
fr:
- "Lis chaque information avec sa clé : `item[\"time\"]` et `item[\"title\"]`."
- "`print(item[\"time\"], \"-\", item[\"title\"])`"
en:
- "Read each piece of information with its key: `item[\"time\"]` and `item[\"title\"]`."
- "`print(item[\"time\"], \"-\", item[\"title\"])`"
solution: |
agenda = [
{"time": "10h", "title": "Dentiste"},
{"time": "20h", "title": "Cinéma"},
]
for item in agenda:
print(item["time"], "-", item["title"])
- type: explain
voice: true
text:
fr: "Pour chercher, on parcourt la liste et on garde les éléments qui conviennent. `\"ne\" in \"Cinéma\"` vaut True si le texte contient ces lettres. On range les éléments trouvés dans une nouvelle liste, que la fonction renvoie."
en: "To search, we go through the list and keep the items that match. `\"ne\" in \"Cinéma\"` is True if the text contains those letters. We put the items found in a new list, which the function returns."
- type: code
starter: |
agenda = [
{"time": "10h", "title": "Dentiste"},
{"time": "19h", "title": "Dîner"},
{"time": "20h", "title": "Cinéma"},
]
def search(agenda, word):
results = []
return results
for item in search(agenda, input("Mot cherché ? ")):
print(item["time"], item["title"])
instruction:
fr: Complète `search()` pour qu'elle renvoie les rendez-vous dont le titre contient le mot cherché.
en: Complete `search()` so that it returns the appointments whose title contains the word searched.
tests:
- kind: stdout_matches_regex
value: "^[^\\n]*10h Dentiste\\n$"
inputs:
- Dent
message:
fr: "Avec Dent, il faut afficher seulement 10h Dentiste."
en: "With Dent, it must show only 10h Dentiste."
- kind: stdout_matches_regex
value: "^[^\\n]*10h Dentiste\\n19h Dîner\\n$"
inputs:
- e
message:
fr: "Avec e, il faut afficher 10h Dentiste puis 19h Dîner (Cinéma n'a pas de e sans accent)."
en: "With e, it must show 10h Dentiste then 19h Dîner (Cinéma has no unaccented e)."
- kind: stdout_matches_regex
value: "^[^\\n]*$"
inputs:
- zzz
message:
fr: "Avec zzz, rien ne doit être affiché en dehors de la question."
en: "With zzz, nothing must be shown apart from the question."
hints:
fr:
- "Dans une boucle sur `agenda`, teste `word in item[\"title\"]`."
- "Si le test est vrai, `results.append(item)`."
en:
- "In a loop over `agenda`, test `word in item[\"title\"]`."
- "If the test is true, `results.append(item)`."
solution: |
agenda = [
{"time": "10h", "title": "Dentiste"},
{"time": "19h", "title": "Dîner"},
{"time": "20h", "title": "Cinéma"},
]
def search(agenda, word):
results = []
for item in agenda:
if word in item["title"]:
results.append(item)
return results
for item in search(agenda, input("Mot cherché ? ")):
print(item["time"], item["title"])
mission:
title:
fr: Mini-agenda, version 2
en: Mini agenda, version 2
goal:
fr: "Chaque rendez-vous est un dictionnaire avec `time` et `title`. Complète `add_appointment`, `show_agenda` (une ligne « 10h | Dentiste » par rendez-vous, comme un tableau) et `search`."
en: "Each appointment is a dictionary with `time` and `title`. Complete `add_appointment`, `show_agenda` (one line \"10h | Dentiste\" per appointment, like a table) and `search`."
starter: |
agenda = []
def add_appointment(agenda, time, title):
# Ajoute le dictionnaire {"time": ..., "title": ...} à la liste agenda
pass
def show_agenda(agenda):
# Affiche une ligne par rendez-vous : "10h | Dentiste"
pass
def search(agenda, word):
# Renvoie la liste des rendez-vous dont le titre contient word
return []
add_appointment(agenda, "10h", "Dentiste")
add_appointment(agenda, "20h", "Cinéma")
add_appointment(agenda, "19h", "Dîner")
show_agenda(agenda)
found = search(agenda, input("Mot cherché ? "))
show_agenda(found)
tests:
- kind: stdout_matches_regex
value: "^10h \\| Dentiste\\n20h \\| Cinéma\\n19h \\| Dîner\\n[^\\n]*10h \\| Dentiste\\n19h \\| Dîner\\n$"
inputs:
- e
message:
fr: "Le tableau complet doit s'afficher, puis les résultats de la recherche (avec e : Dentiste et Dîner)."
en: "The full table must be shown, then the search results (with e: Dentiste and Dîner)."
- kind: stdout_matches_regex
value: "^10h \\| Dentiste\\n20h \\| Cinéma\\n19h \\| Dîner\\n[^\\n]*$"
inputs:
- zzz
message:
fr: "Sans résultat, seul le tableau complet et la question doivent apparaître."
en: "With no result, only the full table and the question must appear."
- kind: var_type_is
name: found
value: list
inputs:
- e
- kind: code_contains
value: .append(
message:
fr: Utilise append pour ajouter à une liste.
en: Use append to add to a list.
solution: |
agenda = []
def add_appointment(agenda, time, title):
agenda.append({"time": time, "title": title})
def show_agenda(agenda):
for item in agenda:
print(item["time"], "|", item["title"])
def search(agenda, word):
results = []
for item in agenda:
if word in item["title"]:
results.append(item)
return results
add_appointment(agenda, "10h", "Dentiste")
add_appointment(agenda, "20h", "Cinéma")
add_appointment(agenda, "19h", "Dîner")
show_agenda(agenda)
found = search(agenda, input("Mot cherché ? "))
show_agenda(found)
reward_sound: success_small
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+38
View File
@@ -0,0 +1,38 @@
{
"en": {
"821fb59a96742789": {
"text": "A file only holds text: to read a number back, we convert it with int(). We can also save several pieces of information per line by separating them with a symbol, like 10h|Dentist, then get them back with line.split(\"|\").",
"voice": "en_US-ljspeech-high"
},
"b2d695b3cb944b9a": {
"text": "To write several lines, we end each text with \\n, the line break. To read them back, we go through the file with for line in file:, and line.strip() removes the line break from each line.",
"voice": "en_US-ljspeech-high"
},
"b989ccad83c88205": {
"text": "A file lets you keep information. We open it with open, giving the mode: \"w\" to write and \"r\" to read. With with, Python closes the file by itself. In PyQuest, only the files in the data/ folder are kept when you close the page.",
"voice": "en_US-ljspeech-high"
},
"ffa7efde6e083ddc": {
"text": "For the mission, import os then os.path.exists(path) tells whether a file already exists. Your agenda will be saved in data/agenda.txt, one line per appointment. Close PyQuest and reopen it: the file will still be there.",
"voice": "en_US-ljspeech-high"
}
},
"fr": {
"483e096cf30497f4": {
"text": "Pour la mission, import os puis os.path.exists(chemin) dit si un fichier existe déjà. Ton agenda sera sauvegardé dans data/agenda.txt, une ligne par rendez-vous. Ferme PyQuest et rouvre-le : le fichier sera toujours là.",
"voice": "fr_FR-siwis-medium"
},
"49f34a662c74caad": {
"text": "Pour écrire plusieurs lignes, on termine chaque texte par \\n, le retour à la ligne. Pour les relire, on parcourt le fichier avec for line in file:, et line.strip() retire le retour à la ligne de chaque ligne.",
"voice": "fr_FR-siwis-medium"
},
"7bf51faefc539056": {
"text": "Un fichier permet de garder des informations. On l'ouvre avec open, en indiquant le mode : \"w\" pour écrire et \"r\" pour lire. Avec with, Python referme le fichier tout seul. Dans PyQuest, seuls les fichiers du dossier data/ sont conservés quand tu fermes la page.",
"voice": "fr_FR-siwis-medium"
},
"d2a8f02690d28132": {
"text": "Un fichier ne contient que du texte : pour relire un nombre, on le convertit avec int(). On peut aussi sauvegarder plusieurs informations par ligne en les séparant par un symbole, comme 10h|Dentiste, puis les retrouver avec ligne.split(\"|\").",
"voice": "fr_FR-siwis-medium"
}
}
}
+204
View File
@@ -0,0 +1,204 @@
id: 10-files
title:
fr: Garder une trace
en: Keeping a record
difficulty: 4
xp: 90
requires:
- 09-dicts
steps:
- type: explain
voice: true
text:
fr: "Un fichier permet de garder des informations. On l'ouvre avec `open`, en indiquant le mode : \"w\" pour écrire et \"r\" pour lire. Avec `with`, Python referme le fichier tout seul. Dans PyQuest, seuls les fichiers du dossier `data/` sont conservés quand tu fermes la page."
en: "A file lets you keep information. We open it with `open`, giving the mode: \"w\" to write and \"r\" to read. With `with`, Python closes the file by itself. In PyQuest, only the files in the `data/` folder are kept when you close the page."
- type: code
starter: |
with open("data/note.txt", "w") as file:
file.write("Bonjour fichier")
with open("data/note.txt", "r") as file:
print(file.read())
instruction:
fr: Écris Salut PyQuest dans le fichier, puis relis-le pour l'afficher.
en: Write Salut PyQuest in the file, then read it back to show it.
tests:
- kind: stdout_equals
value: "Salut PyQuest\n"
hints:
fr:
- "Change seulement le texte donné à `file.write`."
en:
- "Only change the text given to `file.write`."
solution: |
with open("data/note.txt", "w") as file:
file.write("Salut PyQuest")
with open("data/note.txt", "r") as file:
print(file.read())
- type: explain
voice: true
text:
fr: "Pour écrire plusieurs lignes, on termine chaque texte par `\\n`, le retour à la ligne. Pour les relire, on parcourt le fichier avec `for line in file:`, et `line.strip()` retire le retour à la ligne de chaque ligne."
en: "To write several lines, we end each text with `\\n`, the line break. To read them back, we go through the file with `for line in file:`, and `line.strip()` removes the line break from each line."
- type: code
starter: |
names = ["Alice", "Bob", "Chloé"]
with open("data/names.txt", "w") as file:
for name in names:
pass
with open("data/names.txt", "r") as file:
for line in file:
print(line.strip())
instruction:
fr: "Complète la boucle d'écriture pour que chaque prénom soit écrit sur sa propre ligne."
en: "Complete the writing loop so that each name is written on its own line."
tests:
- kind: stdout_equals
value: "Alice\nBob\nChloé\n"
hints:
fr:
- "Remplace `pass` par une écriture du prénom."
- "`file.write(name + \"\\n\")`"
en:
- "Replace `pass` with a write of the name."
- "`file.write(name + \"\\n\")`"
solution: |
names = ["Alice", "Bob", "Chloé"]
with open("data/names.txt", "w") as file:
for name in names:
file.write(name + "\n")
with open("data/names.txt", "r") as file:
for line in file:
print(line.strip())
- type: explain
voice: true
text:
fr: "Un fichier ne contient que du texte : pour relire un nombre, on le convertit avec `int()`. On peut aussi sauvegarder plusieurs informations par ligne en les séparant par un symbole, comme `10h|Dentiste`, puis les retrouver avec `ligne.split(\"|\")`."
en: "A file only holds text: to read a number back, we convert it with `int()`. We can also save several pieces of information per line by separating them with a symbol, like `10h|Dentist`, then get them back with `line.split(\"|\")`."
- type: code
starter: |
with open("data/scores.txt", "w") as file:
file.write("12\n7\n19\n")
total = 0
with open("data/scores.txt", "r") as file:
for line in file:
pass
print(total)
instruction:
fr: Additionne les nombres lus dans le fichier, pour que `total` vaille 38.
en: Add up the numbers read from the file, so that `total` is 38.
tests:
- kind: var_equals
name: total
value: 38
- kind: stdout_equals
value: "38\n"
hints:
fr:
- "Chaque ligne est un texte : convertis-la avec `int(line)`."
- "`total = total + int(line)`"
en:
- "Each line is text: convert it with `int(line)`."
- "`total = total + int(line)`"
solution: |
with open("data/scores.txt", "w") as file:
file.write("12\n7\n19\n")
total = 0
with open("data/scores.txt", "r") as file:
for line in file:
total = total + int(line)
print(total)
- type: explain
voice: true
text:
fr: "Pour la mission, `import os` puis `os.path.exists(chemin)` dit si un fichier existe déjà. Ton agenda sera sauvegardé dans `data/agenda.txt`, une ligne par rendez-vous. Ferme PyQuest et rouvre-le : le fichier sera toujours là."
en: "For the mission, `import os` then `os.path.exists(path)` tells whether a file already exists. Your agenda will be saved in `data/agenda.txt`, one line per appointment. Close PyQuest and reopen it: the file will still be there."
mission:
title:
fr: Mini-agenda, version 3
en: Mini agenda, version 3
goal:
fr: "Complète `save_agenda` (une ligne « 10h|Dentiste » par rendez-vous dans `data/agenda.txt`) et `load_agenda` (renvoie la liste de dictionnaires lue dans le fichier, ou une liste vide s'il n'existe pas). Le programme affiche l'agenda relu."
en: "Complete `save_agenda` (one line \"10h|Dentist\" per appointment in `data/agenda.txt`) and `load_agenda` (returns the list of dictionaries read from the file, or an empty list if it does not exist). The program shows the agenda read back."
starter: |
import os
PATH = "data/agenda.txt"
def save_agenda(agenda):
# Écris chaque rendez-vous sur une ligne : "10h|Dentiste"
pass
def load_agenda():
# Si le fichier existe, relis-le et renvoie la liste de dictionnaires ; sinon renvoie []
return []
title = input("Titre du dernier rendez-vous ? ")
agenda = [
{"time": "10h", "title": "Dentiste"},
{"time": "20h", "title": "Cinéma"},
{"time": "21h", "title": title},
]
save_agenda(agenda)
loaded = load_agenda()
for item in loaded:
print(item["time"], "|", item["title"])
tests:
- kind: stdout_matches_regex
value: "^[^\\n]*10h \\| Dentiste\\n20h \\| Cinéma\\n21h \\| Concert\\n$"
inputs:
- Concert
message:
fr: "Avec Concert, l'agenda relu doit afficher les trois rendez-vous."
en: "With Concert, the agenda read back must show the three appointments."
- kind: stdout_matches_regex
value: "^[^\\n]*10h \\| Dentiste\\n20h \\| Cinéma\\n21h \\| Yoga\\n$"
inputs:
- Yoga
- kind: var_type_is
name: loaded
value: list
inputs:
- Concert
- kind: code_contains
value: with open(
message:
fr: Utilise with open(...) pour lire et écrire le fichier.
en: Use with open(...) to read and write the file.
solution: |
import os
PATH = "data/agenda.txt"
def save_agenda(agenda):
with open(PATH, "w") as file:
for item in agenda:
file.write(item["time"] + "|" + item["title"] + "\n")
def load_agenda():
agenda = []
if os.path.exists(PATH):
with open(PATH, "r") as file:
for line in file:
time, title = line.strip().split("|")
agenda.append({"time": time, "title": title})
return agenda
title = input("Titre du dernier rendez-vous ? ")
agenda = [
{"time": "10h", "title": "Dentiste"},
{"time": "20h", "title": "Cinéma"},
{"time": "21h", "title": title},
]
save_agenda(agenda)
loaded = load_agenda()
for item in loaded:
print(item["time"], "|", item["title"])
reward_sound: success_big
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+38
View File
@@ -0,0 +1,38 @@
{
"en": {
"3485ed09f361fcef": {
"text": "One last tool: datetime. With from datetime import date, date(1789, 7, 14) creates a date, and we read its parts with .year, .month and .day. date.today() gives today's date.",
"voice": "en_US-ljspeech-high"
},
"3b009f63d8254f91": {
"text": "The string module holds ready-made lists of characters: string.ascii_lowercase (lowercase letters) and string.digits (the digits). We can glue them with +. And \"\".join(list) glues the items of a list of letters into a single text.",
"voice": "en_US-ljspeech-high"
},
"7630f1f246354f0a": {
"text": "Python comes with a big toolbox: modules. We load one with import, then use its tools with a dot: math.sqrt(16) computes the square root. No need to rewrite everything!",
"voice": "en_US-ljspeech-high"
},
"8052d50a4317efff": {
"text": "The random module can also shuffle: random.shuffle(list) changes the order of a list, in place. And random.choice(text) picks one character at random from a text.",
"voice": "en_US-ljspeech-high"
}
},
"fr": {
"1817ecb69edf279b": {
"text": "Python vient avec une grande boîte à outils : les modules. On en charge un avec import, puis on utilise ses outils avec un point : math.sqrt(16) calcule la racine carrée. Pas besoin de tout réécrire !",
"voice": "fr_FR-siwis-medium"
},
"8789fd1964baf52f": {
"text": "Le module string contient des listes de caractères toutes prêtes : string.ascii_lowercase (les lettres minuscules) et string.digits (les chiffres). On peut les coller avec +. Et \"\".join(liste) colle les éléments d'une liste de lettres en un seul texte.",
"voice": "fr_FR-siwis-medium"
},
"93fb523d197d048f": {
"text": "Dernier outil : datetime. Avec from datetime import date, date(1789, 7, 14) crée une date, et on lit ses morceaux avec .year, .month et .day. date.today() donne la date d'aujourd'hui.",
"voice": "fr_FR-siwis-medium"
},
"f129239ca80ce0fa": {
"text": "Le module random sait aussi mélanger : random.shuffle(liste) change l'ordre d'une liste, sur place. Et random.choice(texte) tire un caractère au hasard dans un texte.",
"voice": "fr_FR-siwis-medium"
}
}
}
+200
View File
@@ -0,0 +1,200 @@
id: 11-libraries
title:
fr: Utiliser des bibliothèques
en: Using libraries
difficulty: 4
xp: 80
requires:
- 10-files
steps:
- type: explain
voice: true
text:
fr: "Python vient avec une grande boîte à outils : les modules. On en charge un avec `import`, puis on utilise ses outils avec un point : `math.sqrt(16)` calcule la racine carrée. Pas besoin de tout réécrire !"
en: "Python comes with a big toolbox: modules. We load one with `import`, then use its tools with a dot: `math.sqrt(16)` computes the square root. No need to rewrite everything!"
- type: code
starter: |
import math
print(math.sqrt(16))
instruction:
fr: Affiche la racine carrée de 81.
en: Show the square root of 81.
tests:
- kind: stdout_equals
value: "9.0\n"
- kind: code_contains
value: math.sqrt
message:
fr: Utilise math.sqrt.
en: Use math.sqrt.
hints:
fr:
- "Change le nombre donné à `math.sqrt`."
en:
- "Change the number given to `math.sqrt`."
solution: |
import math
print(math.sqrt(81))
- type: explain
voice: true
text:
fr: "Le module `string` contient des listes de caractères toutes prêtes : `string.ascii_lowercase` (les lettres minuscules) et `string.digits` (les chiffres). On peut les coller avec `+`. Et `\"\".join(liste)` colle les éléments d'une liste de lettres en un seul texte."
en: "The `string` module holds ready-made lists of characters: `string.ascii_lowercase` (lowercase letters) and `string.digits` (the digits). We can glue them with `+`. And `\"\".join(list)` glues the items of a list of letters into a single text."
- type: code
starter: |
import string
letters = string.ascii_lowercase
print(len(letters))
instruction:
fr: "Combien de caractères différents a-t-on en combinant les lettres minuscules et les chiffres ? Affiche-le avec `len()`."
en: "How many different characters do we have by combining lowercase letters and digits? Show it with `len()`."
tests:
- kind: stdout_equals
value: "36\n"
- kind: code_contains
value: string.digits
message:
fr: Utilise string.digits.
en: Use string.digits.
hints:
fr:
- "Colle les deux avec `+` avant de compter."
- "`letters = string.ascii_lowercase + string.digits`"
en:
- "Glue the two with `+` before counting."
- "`letters = string.ascii_lowercase + string.digits`"
solution: |
import string
letters = string.ascii_lowercase + string.digits
print(len(letters))
- type: explain
voice: true
text:
fr: "Le module `random` sait aussi mélanger : `random.shuffle(liste)` change l'ordre d'une liste, sur place. Et `random.choice(texte)` tire un caractère au hasard dans un texte."
en: "The `random` module can also shuffle: `random.shuffle(list)` changes the order of a list, in place. And `random.choice(text)` picks one character at random from a text."
- type: code
starter: |
import random
letters = ["a", "b", "c", "d"]
print("".join(letters))
instruction:
fr: Mélange la liste avec `random.shuffle` avant de l'afficher. Relance plusieurs fois pour voir l'ordre changer.
en: Shuffle the list with `random.shuffle` before showing it. Run it several times to see the order change.
tests:
- kind: code_contains
value: random.shuffle
message:
fr: Utilise random.shuffle(letters).
en: Use random.shuffle(letters).
- kind: stdout_matches_regex
value: "^(?!.*(.).*\\1)[abcd]{4}\\n$"
message:
fr: Il faut afficher les quatre lettres a, b, c, d, chacune une seule fois.
en: The four letters a, b, c, d must be shown, each exactly once.
hints:
fr:
- "`random.shuffle(letters)` ne renvoie rien : il modifie la liste."
- "Appelle-le sur sa propre ligne, avant le `print`."
en:
- "`random.shuffle(letters)` returns nothing: it changes the list."
- "Call it on its own line, before the `print`."
solution: |
import random
letters = ["a", "b", "c", "d"]
random.shuffle(letters)
print("".join(letters))
- type: explain
voice: true
text:
fr: "Dernier outil : `datetime`. Avec `from datetime import date`, `date(1789, 7, 14)` crée une date, et on lit ses morceaux avec `.year`, `.month` et `.day`. `date.today()` donne la date d'aujourd'hui."
en: "One last tool: `datetime`. With `from datetime import date`, `date(1789, 7, 14)` creates a date, and we read its parts with `.year`, `.month` and `.day`. `date.today()` gives today's date."
- type: code
starter: |
from datetime import date
day = date(2000, 1, 1)
print(day.year)
instruction:
fr: Crée la date du 14 juillet 1789 et affiche son mois.
en: Create the date of 14 July 1789 and show its month.
tests:
- kind: stdout_equals
value: "7\n"
- kind: code_contains
value: .month
message:
fr: Lis le mois avec .month.
en: Read the month with .month.
hints:
fr:
- "Les trois nombres de `date()` sont l'année, le mois et le jour."
- "`day = date(1789, 7, 14)` puis `print(day.month)`."
en:
- "The three numbers of `date()` are the year, the month and the day."
- "`day = date(1789, 7, 14)` then `print(day.month)`."
solution: |
from datetime import date
day = date(1789, 7, 14)
print(day.month)
mission:
title:
fr: Générateur de mots de passe, version 2
en: Password generator, version 2
goal:
fr: "Demande la longueur avec `int(input())` (sans texte de question), puis affiche un mot de passe de cette longueur qui contient au moins une minuscule, une majuscule et un chiffre. Garantis-le : tire une lettre de chaque sorte, complète avec des caractères au hasard, puis mélange."
en: "Ask for the length with `int(input())` (without question text), then show a password of that length that contains at least one lowercase letter, one uppercase letter and one digit. Guarantee it: pick one character of each kind, fill up with random characters, then shuffle."
starter: |
import random
import string
length = int(input())
password = []
# Ajoute une minuscule, une majuscule et un chiffre, complète jusqu'à length, mélange
print("".join(password))
tests:
- kind: stdout_matches_regex
value: "^(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])[A-Za-z0-9]{12}\\n$"
inputs:
- "12"
message:
fr: "Avec 12, il faut afficher 12 caractères (lettres et chiffres) avec au moins une minuscule, une majuscule et un chiffre."
en: "With 12, it must show 12 characters (letters and digits) with at least one lowercase, one uppercase and one digit."
- kind: stdout_matches_regex
value: "^(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])[A-Za-z0-9]{20}\\n$"
inputs:
- "20"
- kind: stdout_matches_regex
value: "^(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])[A-Za-z0-9]{3}\\n$"
inputs:
- "3"
message:
fr: "Même avec 3, les trois sortes de caractères doivent être présentes."
en: "Even with 3, all three kinds of characters must be present."
- kind: code_contains
value: random.shuffle
message:
fr: Mélange le mot de passe avec random.shuffle.
en: Shuffle the password with random.shuffle.
solution: |
import random
import string
length = int(input())
password = [
random.choice(string.ascii_lowercase),
random.choice(string.ascii_uppercase),
random.choice(string.digits),
]
pool = string.ascii_letters + string.digits
while len(password) < length:
password.append(random.choice(pool))
random.shuffle(password)
print("".join(password))
reward_sound: success_small
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+30
View File
@@ -0,0 +1,30 @@
{
"en": {
"0b31ad7aad82d0c3": {
"text": "An error stops the program, but we can plan for it. With try, we attempt some code; with except, we say what to do if a specific error happens. The program carries on instead of crashing.",
"voice": "en_US-ljspeech-high"
},
"138a92b691cd17b1": {
"text": "We can plan for several errors with several except blocks, each for a specific error. It is better to name the expected error than to catch everything: otherwise we also hide real bugs. For example, dividing by zero raises ZeroDivisionError.",
"voice": "en_US-ljspeech-high"
},
"229531dd1cfbce9d": {
"text": "A robust program asks again as long as the input is invalid. We combine while True:, try and break: we try to convert, we leave the loop if it works, and we show a message if it fails.",
"voice": "en_US-ljspeech-high"
}
},
"fr": {
"2a54bbd63acd06bb": {
"text": "Une erreur arrête le programme, mais on peut la prévoir. Avec try, on essaie du code ; avec except, on dit quoi faire si une erreur précise se produit. Le programme continue au lieu de planter.",
"voice": "fr_FR-siwis-medium"
},
"3c4ae2941dd9524b": {
"text": "On peut prévoir plusieurs erreurs avec plusieurs except, chacun pour une erreur précise. Il vaut mieux nommer l'erreur attendue que tout attraper : sinon on cache aussi les vrais bugs. Par exemple, diviser par zéro lève ZeroDivisionError.",
"voice": "fr_FR-siwis-medium"
},
"bedd252b7fa29e83": {
"text": "Un programme robuste redemande tant que la saisie est invalide. On combine while True:, try et break : on essaie de convertir, on sort de la boucle si ça marche, et on affiche un message si ça échoue.",
"voice": "fr_FR-siwis-medium"
}
}
}
+222
View File
@@ -0,0 +1,222 @@
id: 12-errors
title:
fr: Gérer les erreurs
en: Handling errors
difficulty: 4
xp: 80
requires:
- 11-libraries
steps:
- type: explain
voice: true
text:
fr: "Une erreur arrête le programme, mais on peut la prévoir. Avec `try`, on essaie du code ; avec `except`, on dit quoi faire si une erreur précise se produit. Le programme continue au lieu de planter."
en: "An error stops the program, but we can plan for it. With `try`, we attempt some code; with `except`, we say what to do if a specific error happens. The program carries on instead of crashing."
- type: code
starter: |
text = input("Un nombre ? ")
number = int(text)
print(number * 2)
instruction:
fr: "Si l'utilisateur tape autre chose qu'un nombre, affiche Ce n'est pas un nombre au lieu de planter."
en: "If the user types something other than a number, show Ce n'est pas un nombre instead of crashing."
tests:
- kind: stdout_matches_regex
value: "^[^\\n]*42\\n$"
inputs:
- "21"
message:
fr: "Avec 21, il faut toujours afficher 42."
en: "With 21, it must still show 42."
- kind: stdout_matches_regex
value: "^[^\\n]*Ce n'est pas un nombre\\n$"
inputs:
- abc
message:
fr: "Avec abc, il faut afficher Ce n'est pas un nombre."
en: "With abc, it must show Ce n'est pas un nombre."
- kind: code_contains
value: except ValueError
message:
fr: Attrape précisément l'erreur ValueError.
en: Catch precisely the ValueError error.
hints:
fr:
- "Mets `int(text)` et le `print` dans un bloc `try:`."
- "Ajoute `except ValueError:` suivi du message à afficher."
en:
- "Put `int(text)` and the `print` in a `try:` block."
- "Add `except ValueError:` followed by the message to show."
solution: |
text = input("Un nombre ? ")
try:
number = int(text)
print(number * 2)
except ValueError:
print("Ce n'est pas un nombre")
- type: explain
voice: true
text:
fr: "On peut prévoir plusieurs erreurs avec plusieurs `except`, chacun pour une erreur précise. Il vaut mieux nommer l'erreur attendue que tout attraper : sinon on cache aussi les vrais bugs. Par exemple, diviser par zéro lève `ZeroDivisionError`."
en: "We can plan for several errors with several `except` blocks, each for a specific error. It is better to name the expected error than to catch everything: otherwise we also hide real bugs. For example, dividing by zero raises `ZeroDivisionError`."
- type: code
starter: |
a = int(input("a ? "))
b = int(input("b ? "))
print(a / b)
instruction:
fr: "Évite le plantage quand b vaut 0 : affiche Division par zéro impossible."
en: "Avoid the crash when b is 0: show Division par zéro impossible."
tests:
- kind: stdout_matches_regex
value: "^[^\\n]*2.5\\n$"
inputs:
- "10"
- "4"
message:
fr: "Avec 10 et 4, il faut afficher 2.5."
en: "With 10 and 4, it must show 2.5."
- kind: stdout_matches_regex
value: "^[^\\n]*Division par zéro impossible\\n$"
inputs:
- "5"
- "0"
message:
fr: "Avec 5 et 0, il faut afficher Division par zéro impossible."
en: "With 5 and 0, it must show Division par zéro impossible."
- kind: code_contains
value: ZeroDivisionError
message:
fr: Attrape l'erreur ZeroDivisionError.
en: Catch the ZeroDivisionError error.
hints:
fr:
- "Seul le calcul `a / b` peut provoquer l'erreur : mets-le dans le `try`."
- "`except ZeroDivisionError:` puis le message."
en:
- "Only the calculation `a / b` can cause the error: put it in the `try`."
- "`except ZeroDivisionError:` then the message."
solution: |
a = int(input("a ? "))
b = int(input("b ? "))
try:
print(a / b)
except ZeroDivisionError:
print("Division par zéro impossible")
- type: explain
voice: true
text:
fr: "Un programme robuste redemande tant que la saisie est invalide. On combine `while True:`, `try` et `break` : on essaie de convertir, on sort de la boucle si ça marche, et on affiche un message si ça échoue."
en: "A robust program asks again as long as the input is invalid. We combine `while True:`, `try` and `break`: we try to convert, we leave the loop if it works, and we show a message if it fails."
- type: code
starter: |
while True:
text = input("Ton âge ? ")
age = int(text)
break
print("Tu as", age, "ans")
instruction:
fr: "Redemande l'âge tant que la saisie n'est pas un nombre, en affichant Nombre invalide à chaque erreur."
en: "Ask for the age again as long as the input is not a number, showing Nombre invalide at each error."
tests:
- kind: stdout_matches_regex
value: "^[^\\n]*Tu as 15 ans\\n$"
inputs:
- "15"
message:
fr: "Avec 15 du premier coup, seule la phrase finale doit apparaître."
en: "With 15 at the first try, only the final sentence must appear."
- kind: stdout_matches_regex
value: "^[^\\n]*Nombre invalide\\n[^\\n]*Nombre invalide\\n[^\\n]*Tu as 15 ans\\n$"
inputs:
- abc
- x
- "15"
message:
fr: "Avec abc, x puis 15, il faut afficher deux fois Nombre invalide puis Tu as 15 ans."
en: "With abc, x then 15, it must show Nombre invalide twice then Tu as 15 ans."
hints:
fr:
- "Mets la conversion `int(text)` et le `break` dans `try:`, de sorte que `break` ne soit atteint que si la conversion réussit."
- "Ajoute `except ValueError:` avec `print(\"Nombre invalide\")`."
en:
- "Put the conversion `int(text)` and the `break` in `try:`, so that `break` is only reached if the conversion succeeds."
- "Add `except ValueError:` with `print(\"Nombre invalide\")`."
solution: |
while True:
text = input("Ton âge ? ")
try:
age = int(text)
break
except ValueError:
print("Nombre invalide")
print("Tu as", age, "ans")
mission:
title:
fr: Calculatrice de pourboire robuste
en: Robust tip calculator
goal:
fr: "Redemande le montant de l'addition (`float`) tant qu'il est invalide (message Montant invalide), puis le pourcentage de pourboire tant qu'il est invalide (message Pourcentage invalide). Calcule `total` = montant + montant × pourcentage / 100 et affiche « Total : … ». Le programme ne doit jamais planter."
en: "Ask for the bill amount (`float`) again as long as it is invalid (message Montant invalide), then the tip percentage as long as it is invalid (message Pourcentage invalide). Compute `total` = amount + amount × percentage / 100 and show \"Total : …\". The program must never crash."
starter: |
# Calculatrice de pourboire robuste
bill = float(input("Montant de l'addition ? "))
rate = float(input("Pourcentage de pourboire ? "))
tip = bill * rate / 100
total = bill + tip
print("Total :", total)
tests:
- kind: var_equals
name: total
value: 57.5
inputs:
- abc
- "50"
- x
- "15"
message:
fr: "Avec abc, 50, x puis 15, total doit valoir 57.5."
en: "With abc, 50, x then 15, total must be 57.5."
- kind: stdout_matches_regex
value: "^[^\\n]*Montant invalide\\n[^\\n]*[^\\n]*Pourcentage invalide\\n[^\\n]*Total : 57.5\\n$"
inputs:
- abc
- "50"
- x
- "15"
message:
fr: "Il faut afficher Montant invalide, puis Pourcentage invalide, puis Total : 57.5."
en: "It must show Montant invalide, then Pourcentage invalide, then Total : 57.5."
- kind: var_equals
name: total
value: 110
inputs:
- "100"
- "10"
message:
fr: "Avec 100 et 10, total doit valoir 110."
en: "With 100 and 10, total must be 110."
- kind: code_contains
value: except ValueError
message:
fr: Attrape l'erreur ValueError.
en: Catch the ValueError error.
solution: |
while True:
try:
bill = float(input("Montant de l'addition ? "))
break
except ValueError:
print("Montant invalide")
while True:
try:
rate = float(input("Pourcentage de pourboire ? "))
break
except ValueError:
print("Pourcentage invalide")
tip = bill * rate / 100
total = bill + tip
print("Total :", total)
reward_sound: success_small
+6 -1
View File
@@ -8,6 +8,11 @@
{ "id": "04-math", "requires": ["03-input"] },
{ "id": "05-decide", "requires": ["04-math"] },
{ "id": "06-lists", "requires": ["05-decide"] },
{ "id": "07-while", "requires": ["06-lists"] }
{ "id": "07-while", "requires": ["06-lists"] },
{ "id": "08-functions", "requires": ["07-while"] },
{ "id": "09-dicts", "requires": ["08-functions"] },
{ "id": "10-files", "requires": ["09-dicts"] },
{ "id": "11-libraries", "requires": ["10-files"] },
{ "id": "12-errors", "requires": ["11-libraries"] }
]
}
+33 -5
View File
@@ -259,15 +259,15 @@ test('navigation : lien direct vers un niveau, tiroirs accessibles, précédent/
// Lien direct vers le niveau 05.
await page.goto(`${base}#/levels/05-decide`);
await page.waitForSelector('.explain', { timeout: 60000 });
assert.match(await page.textContent('#level-current'), /Niveau 6 sur 8 · Décider/);
assert.match(await page.textContent('#level-current'), /Niveau 6 sur \d+ · Décider/);
assert.match(await page.textContent('.notebook-status'), /Étape 1 sur/);
// Précédent / suivant changent de niveau et l'URL ; le bouton retour du navigateur revient.
await page.locator('#level-next').click();
await page.waitForFunction(() => document.querySelector('#level-current').textContent.includes('Niveau 7 sur 8'));
await page.waitForFunction(() => document.querySelector('#level-current').textContent.includes('Niveau 7 sur '));
assert.equal(new URL(page.url()).hash, '#/levels/06-lists');
await page.goBack();
await page.waitForFunction(() => document.querySelector('#level-current').textContent.includes('Niveau 6 sur 8'));
await page.waitForFunction(() => document.querySelector('#level-current').textContent.includes('Niveau 6 sur '));
// Tiroir « Niveaux » : le reste de la page devient inerte, Échap ferme et rend le focus au bouton.
const toggle = page.locator('#levels-toggle');
@@ -276,7 +276,7 @@ test('navigation : lien direct vers un niveau, tiroirs accessibles, précédent/
assert.equal(await toggle.getAttribute('aria-expanded'), 'true');
assert.equal(await page.locator('#app-root').getAttribute('inert'), '');
assert.match(await page.textContent('.drawer-left .drawer-title'), /Ta progression/);
assert.match(await page.textContent('.progress-count'), /0 niveau\(x\) terminé\(s\) sur 8/);
assert.match(await page.textContent('.progress-count'), /0 niveau\(x\) terminé\(s\) sur \d+/);
await page.keyboard.press('Escape');
await page.locator('.drawer-left.is-open').waitFor({ state: 'hidden' });
assert.equal(await page.locator('#app-root').getAttribute('inert'), null);
@@ -292,7 +292,7 @@ test('navigation : lien direct vers un niveau, tiroirs accessibles, précédent/
// Choisir un niveau dans le tiroir le ferme et l'ouvre.
await openLevelFromDrawer(page, 'Calculer');
await page.waitForFunction(() => document.querySelector('#level-current').textContent.includes('Niveau 5 sur 8'));
await page.waitForFunction(() => document.querySelector('#level-current').textContent.includes('Niveau 5 sur '));
assert.equal(await page.locator('.drawer-left.is-open').count(), 0);
assert.deepEqual(errors, []);
});
@@ -496,3 +496,31 @@ test('éditeur de niveaux (mode auteur) : écrire un niveau, le vérifier, l\'es
assert.equal(await field('steps.1.solution').inputValue(), 'print("b")');
assert.deepEqual(errors, []);
});
test('fichiers : le dossier data/ survit au rechargement, le reste non', { skip, timeout: 120000 }, async () => {
const page = await (await browser.newContext()).newPage();
const errors = [];
page.on('pageerror', (error) => errors.push(error.message));
const open = async () => {
await page.goto(`${base}#/levels/01-hello`);
await page.waitForSelector('.explain', { timeout: 60000 });
await page.locator('.notebook-action button').click();
await page.waitForSelector('.cell');
};
const run = async (code) => {
await page.locator('.cell textarea').fill(code);
await page.locator('.cell-run').click();
await page.waitForFunction(() => document.querySelector('.cell:last-of-type')?.getAttribute('aria-busy') !== 'true');
await page.waitForTimeout(200);
return page.locator('.cell-output').textContent();
};
await open();
assert.equal(await run('with open("data/memo.txt", "w") as f:\n f.write("persistant")\nopen("hors.txt", "w").write("x")\nprint("écrit")'), 'écrit\n');
await page.reload(); // nouvelle session : la mémoire de Python est neuve
await page.waitForSelector('.explain', { timeout: 60000 });
await page.locator('.notebook-action button').click();
await page.waitForSelector('.cell');
assert.equal(await run('import os\nprint(os.path.exists("data/memo.txt"), os.path.exists("hors.txt"))\nprint(open("data/memo.txt").read())'), 'True False\npersistant\n');
assert.deepEqual(errors, []);
});
+1 -1
View File
@@ -5,7 +5,7 @@ const root = new URL('../../', import.meta.url).pathname.replace(/\/$/, '');
const e = new LessonEngine({ levelsUrl: 'http://x/levels/', fetchFn: async (u) => {
try { const t = await readFile(root + new URL(u).pathname, 'utf8'); return { ok: true, text: async () => t }; }
catch { return { ok: false, status: 404 }; } } });
assert.deepEqual((await e.listLevels()).map((l) => l.id), ['00-intro', '01-hello', '02-variables', '03-input', '04-math', '05-decide', '06-lists', '07-while']);
assert.deepEqual((await e.listLevels()).map((l) => l.id), ['00-intro', '01-hello', '02-variables', '03-input', '04-math', '05-decide', '06-lists', '07-while', '08-functions', '09-dicts', '10-files', '11-libraries', '12-errors']);
const s = await e.startLevel('02-variables', 'en');
assert.equal(s.title, 'Variables and types'); assert.equal(s.stepCount, 7);
assert.equal(s.step.type, 'explain');
@@ -23,7 +23,7 @@ test('les solutions de référence passent, les codes de départ échouent', { s
let checked = 0;
for (const id of readdirSync(`${root}levels`).filter((name) => /^\d\d-/.test(name))) {
const { exercises, problems } = await checker.check(load(id));
assert.deepEqual(summary(problems), [], `${id}`);
assert.deepEqual(summary(problems), [], `${id} : ${JSON.stringify(problems)}`);
checked += exercises.length;
}
assert.ok(checked > 0);