, keyin AttributeError"
+ ],
+ "answer": 0,
+ "explanation": "__getattr__ faqat zaxira yöl: language oddiy qidiruv orqali klassda topiladi, faqat mavjud bölmagan theme __getattr__ ga boradi.",
+ "lesson": "python-data-model"
+ },
+ {
+ "question": "Ota klassning __init_subclass__ metodi qaçon işlaydi?",
+ "options": [
+ "Voris klassning har bir obyekti yaratilganda",
+ "Faqat voris klass super().__init__() ni çaqirganda",
+ "Voris klassning biror metodi birinçi marta çaqirilganda",
+ "Voris klassning özi aniqlanganda"
+ ],
+ "answer": 3,
+ "explanation": "__init_subclass__ class operatori voris klass yaratişi bilanoq, yangi klassni cls sifatida olib işlaydi. Şuning uçun u plaginlar registri uçun qulay.",
+ "lesson": "python-data-model"
+ },
+ {
+ "question": "Qaysi qatorlar qanday tartibda çop etiladi?",
+ "code": "from contextlib import ExitStack\nwith ExitStack() as stack:\n stack.callback(print, \"birinçi\")\n stack.callback(print, \"ikkinçi\")\n print(\"tana\")",
+ "options": [
+ "birinçi, ikkinçi, tana",
+ "tana, ikkinçi, birinçi",
+ "tana, birinçi, ikkinçi",
+ "ikkinçi, birinçi, tana"
+ ],
+ "answer": 1,
+ "explanation": "Callbacklar röyxatdan ötkazilganda emas, with bloki tugaganda işlaydi, ExitStack esa ularni teskari tartibda bajaradi.",
+ "lesson": "context-managers-in-depth"
+ },
+ {
+ "question": "Klass körinişidagi kontekst menejeri haqidagi qaysi fikr töğri?",
+ "options": [
+ "__enter__ istisno çaqirsa ham __exit__ baribir çaqiriladi",
+ "__exit__ None qaytarsa, blokdagi istisno yutiladi",
+ "__exit__ rost qiymat qaytarsa, blokdagi istisno yutiladi",
+ "Blok istisno çaqirganda __exit__ uçta None oladi"
+ ],
+ "answer": 2,
+ "explanation": "__exit__ rost qiymat qaytarsa, istisno yutiladi; None yoki False esa uni yuqoriga uzatadi. Uçta None blok normal tugaganini bildiradi.",
+ "lesson": "context-managers-in-depth"
+ },
+ {
+ "question": "Bu kod nimani çop etadi?",
+ "code": "async def fetch(city):\n return f\"{city}: 12,650 söm\"\nasync def main():\n result = fetch(\"Toşkent\")\n print(type(result).__name__)\nawait main()",
+ "options": [
+ "coroutine",
+ "Toşkent: 12,650 söm",
+ "str",
+ "NoneType"
+ ],
+ "answer": 0,
+ "explanation": "async def funksiyasini çaqiriş faqat korutina obyektini yaratadi; uning tanasi await qilinganda işlaydi. Python korutina heç qaçon await qilinmagani haqida ogohlantiriş ham beradi.",
+ "lesson": "async-await"
+ },
+ {
+ "question": "Bu kod nimani çop etadi?",
+ "code": "import asyncio\nasync def fetch(city, delay):\n await asyncio.sleep(delay)\n return city\nasync def main():\n print(await asyncio.gather(fetch(\"Buxoro\", 0.3), fetch(\"Toşkent\", 0.1)))\nawait main()",
+ "options": [
+ "['Toşkent', 'Buxoro']",
+ "Toşkent",
+ "Qaysi sörov birinçi tugaşiga boğliq",
+ "['Buxoro', 'Toşkent']"
+ ],
+ "answer": 3,
+ "explanation": "Toşkent birinçi tugaydi, lekin gather natijalarni ular tugagan tartibda emas, korutinalarni uzatgan tartibingizda qaytaradi.",
+ "lesson": "async-await"
+ },
+ {
+ "question": "Bu kod nimani çop etadi?",
+ "code": "import sys\nshort = [letter for letter in \"abc\"]\nlong = [letter * 10_000 for letter in \"abc\"]\nprint(sys.getsizeof(short) == sys.getsizeof(long))",
+ "options": [
+ "False",
+ "True",
+ "TypeError",
+ "30000"
+ ],
+ "answer": 1,
+ "explanation": "sys.getsizeof faqat röyxat obyektining özini ölçaydi. Röyxat elementlariga havolalarni saqlaydi, şuning uçun satrlarning ölçami hisobga kirmaydi.",
+ "lesson": "memory-and-performance"
+ },
+ {
+ "question": "Bu kod nimani çop etadi?",
+ "code": "class EventEmitter:\n listeners = []\n def subscribe(self, callback):\n self.listeners.append(callback)\nshop, bank = EventEmitter(), EventEmitter()\nshop.subscribe(print)\nprint(len(bank.listeners))",
+ "options": [
+ "0",
+ "AttributeError",
+ "1",
+ "2"
+ ],
+ "answer": 2,
+ "explanation": "listeners klass atributi, şuning uçun shop ham, bank ham bitta röyxatga qöşadi. Har bir emitterga alohida röyxat beriş uçun uni __init__ içida self.listeners = [] bilan yarating.",
+ "lesson": "design-patterns"
+ },
+ {
+ "question": "Sof Python funksiyasi tub sonlarni sanaydi va siz uni oddiy CPython da ikkita katta kiriş maʼlumoti uçun bir vaqtda işga tuşirmoqçisiz. Qaysi vosita haqiqatan ikkita protsessor yadrosini işlatadi?",
+ "options": [
+ "ProcessPoolExecutor",
+ "ThreadPoolExecutor",
+ "asyncio.gather",
+ "Lock bilan ikkita threading.Thread obyekti"
+ ],
+ "answer": 0,
+ "explanation": "GIL tufayli bir vaqtda faqat bitta oqim Python kodini bajaradi, asyncio esa bitta oqimda işlaydi. Har bir jarayonning özining interpretatori va GIL i bor.",
+ "lesson": "threads-and-processes"
+ },
+ {
+ "question": "prices.py from rates import fetch_rate ni bajaradi, keyin fetch_rate() ni çaqiradi. prices.price_in_som testida qaysi patch kurs olişni almaştiradi?",
+ "options": [
+ "patch(\"rates.fetch_rate\")",
+ "patch(\"fetch_rate\")",
+ "patch(\"rates.prices.fetch_rate\")",
+ "patch(\"prices.fetch_rate\")"
+ ],
+ "answer": 3,
+ "explanation": "Import prices içida ikkinçi nom - fetch_rate ni yaratadi. Nomni u aniqlangan joyda emas, kod uni qidiradigan joyda patch qiling.",
+ "lesson": "testing-in-depth"
+ }
+ ]
+}
diff --git a/docs/.vitepress/theme/CodeEditor.vue b/docs/.vitepress/theme/CodeEditor.vue
new file mode 100644
index 0000000..43ce0e3
--- /dev/null
+++ b/docs/.vitepress/theme/CodeEditor.vue
@@ -0,0 +1,64 @@
+
+
+
diff --git a/docs/.vitepress/theme/CodeEnhancer.vue b/docs/.vitepress/theme/CodeEnhancer.vue
new file mode 100644
index 0000000..d3effc1
--- /dev/null
+++ b/docs/.vitepress/theme/CodeEnhancer.vue
@@ -0,0 +1,87 @@
+
+
+
+
+ e.id !== editor.id); editor.onClose?.()" />
+
+
diff --git a/docs/.vitepress/theme/Difficulty.vue b/docs/.vitepress/theme/Difficulty.vue
new file mode 100644
index 0000000..c245394
--- /dev/null
+++ b/docs/.vitepress/theme/Difficulty.vue
@@ -0,0 +1,14 @@
+
+
+
+
diff --git a/docs/.vitepress/theme/LabLink.vue b/docs/.vitepress/theme/LabLink.vue
new file mode 100644
index 0000000..ade9b15
--- /dev/null
+++ b/docs/.vitepress/theme/LabLink.vue
@@ -0,0 +1,27 @@
+
+
+
+
+
diff --git a/docs/.vitepress/theme/Mark.vue b/docs/.vitepress/theme/Mark.vue
new file mode 100644
index 0000000..e693553
--- /dev/null
+++ b/docs/.vitepress/theme/Mark.vue
@@ -0,0 +1,16 @@
+
+
+
+
+
+
diff --git a/docs/.vitepress/theme/Playground.vue b/docs/.vitepress/theme/Playground.vue
new file mode 100644
index 0000000..6064fe4
--- /dev/null
+++ b/docs/.vitepress/theme/Playground.vue
@@ -0,0 +1,126 @@
+
+
+
+
+
+
+
+
+
+
+
+ {{ verdict.kind === 'error' ? '!' : '?' }}
+ {{ t.verdict[verdict.kind] }}
+
{{ t.showExpected }}
{{ verdict.expected }}
+
+
+
{{ t.outputLabel }}
+
{{ output }}
+
+
+ {{ isExercise ? t.exerciseIdle : t.idle }}
+ {{ status }}
+ {{ t.keyHints }}
+
+
diff --git a/docs/.vitepress/theme/Quiz.vue b/docs/.vitepress/theme/Quiz.vue
new file mode 100644
index 0000000..7a4768d
--- /dev/null
+++ b/docs/.vitepress/theme/Quiz.vue
@@ -0,0 +1,110 @@
+
+
+
+
+
{{ quiz.intro }}
+
{{ t.best }} {{ best }} / {{ total }}
+
+
+ -
+
{{ q.question }}
+ {{ q.code }}
+
+
+
+
+
+
+
+
+
+
+ {{ score }} / {{ total }}
+ — {{ score === total ? t.perfect : score >= total * 0.7 ? t.good : t.low }}
+
+
+
+
+
+
diff --git a/docs/.vitepress/theme/i18n.js b/docs/.vitepress/theme/i18n.js
new file mode 100644
index 0000000..1e2d6a5
--- /dev/null
+++ b/docs/.vitepress/theme/i18n.js
@@ -0,0 +1,34 @@
+import { computed } from 'vue'
+import { useData } from 'vitepress'
+
+const messages = {
+ en: {
+ defaultCode: 'print("Hello, world!")',
+ idle: 'Edit the code, then press Run (or Ctrl + Enter).', close: 'Close', outputLabel: 'Output', loading: 'Loading Python… The first run needs an internet connection.',
+ running: 'Running…', packages: 'Loading packages (numpy, pandas, matplotlib)… this can take a few seconds the first time.', noOutput: 'Code ran without errors (no output).', chartAlt: 'Chart', stopped: 'Stopped. The Python session will restart.', loadFailed: 'Python failed to load. Check your connection and try again.',
+ editorLabel: 'Interactive Python editor', inBrowser: 'Python · in your browser', codeLabel: 'Python code',
+ keyHints: 'Ctrl/Cmd + Enter runs the code. Esc, then Tab moves focus out of the editor.',
+ inputsSummary: 'Values for input()', inputsHelp: 'Write each answer on its own line.', inputsLabel: 'Input values',
+ reset: 'Reset', stop: 'Stop', run: '▶ Run', waiting: 'Waiting…', copy: 'Copy', copied: 'Copied',
+ labLink: 'Practice this module in the Python Lab',
+ starterCode: '# Write your solution here\n', exerciseIdle: 'Write your solution, then press Check to compare your output with the expected output (Ctrl + Enter).', exerciseTitle: 'Your solution', check: 'Check', showExpected: 'Show expected output', solveHere: 'Solve in the browser', closeEditor: 'Close editor', runBlock: '▶ Run in editor',
+ verdict: { pass: 'Correct: your output matches the expected output.', fail: 'Not yet: your output is different from the expected output.', error: 'Your code raised an error. Read the message below.', unknown: 'This exercise cannot be checked automatically. Compare with the solution.' }
+ },
+ uz: {
+ defaultCode: 'print("Salom, dunyo!")',
+ idle: 'Kodni tahrirlang va Işga tuşiriş tugmasini bosing (yoki Ctrl + Enter).', close: 'Yopiş', outputLabel: 'Natija', loading: 'Python yuklanmoqda… Birinçi işga tuşirişda internet kerak.',
+ running: 'Bajarilmoqda…', packages: 'Paketlar yuklanmoqda (numpy, pandas, matplotlib)… birinçi safar bir neçta soniya oladi.', noOutput: 'Kod xatosiz bajarildi (natija çiqmadi).', chartAlt: 'Grafik', stopped: 'Töxtatildi. Python seansi qayta işga tuşadi.', loadFailed: 'Python yuklanmadi. Internet aloqasini tekşirib, qayta urinib köring.',
+ editorLabel: 'Interaktiv Python muharriri', inBrowser: 'Python · brauzeringizda', codeLabel: 'Python kodi',
+ keyHints: 'Ctrl/Cmd + Enter kodni işga tuşiradi. Esc, söng Tab fokusni muharrirdan çiqaradi.',
+ inputsSummary: 'input() uçun qiymatlar', inputsHelp: 'Har bir javobni alohida qatorga yozing.', inputsLabel: 'Kiritiladigan qiymatlar',
+ reset: 'Tiklaş', stop: 'Töxtatiş', run: '▶ Işga tuşiriş', waiting: 'Kutilmoqda…', copy: 'Nusxa oliş', copied: 'Nusxa olindi',
+ labLink: 'Bu modulni Python laboratoriyasida maşq qiling',
+ starterCode: '# Yeçimingizni şu yerga yozing\n', exerciseIdle: 'Yeçimingizni yozing, söng natijangizni kutilgan natija bilan soliştiriş uçun Tekşiriş tugmasini bosing (Ctrl + Enter).', exerciseTitle: 'Sizning yeçimingiz', check: 'Tekşiriş', showExpected: 'Kutilgan natijani körsatiş', solveHere: 'Brauzerda yeçiş', closeEditor: 'Muharrirni yopiş', runBlock: '▶ Muharrirda işga tuşiriş',
+ verdict: { pass: 'Töğri: natijangiz kutilgan natijaga mos keladi.', fail: 'Hali emas: natijangiz kutilgan natijadan farq qiladi.', error: 'Kodingiz xato berdi. Quyidagi xabarni öqing.', unknown: 'Bu maşqni avtomatik tekşirib bölmaydi. Yeçim bilan soliştiring.' }
+ }
+}
+
+export function useT() {
+ const { lang } = useData()
+ return computed(() => messages[lang.value?.startsWith('uz') ? 'uz' : 'en'])
+}
diff --git a/docs/.vitepress/theme/index.js b/docs/.vitepress/theme/index.js
new file mode 100644
index 0000000..5601eb3
--- /dev/null
+++ b/docs/.vitepress/theme/index.js
@@ -0,0 +1,42 @@
+import { h } from 'vue'
+import DefaultTheme from 'vitepress/theme'
+import Playground from './Playground.vue'
+import Difficulty from './Difficulty.vue'
+import Mark from './Mark.vue'
+import Quiz from './Quiz.vue'
+import CodeEnhancer from './CodeEnhancer.vue'
+import LabLink from './LabLink.vue'
+import course from '../course.json'
+import './style.css'
+
+// The language switcher keeps the page path and only swaps the /uz/ prefix, but the two
+// languages use different folder names (/lessons/ vs /uz/darslar/ and so on). Map them here.
+const slugs = new Set(course.map(lesson => lesson.slug))
+const pairs = [['lessons/', 'darslar/'], ['checkpoints/', 'nazorat/'], ['playground', 'sinov-maydoni'], ['lab', 'laboratoriya']]
+function localeTarget(href) {
+ const match = href.match(/^(.*?\/)(uz\/)?([a-z-]+\/?)([a-z0-9-]*)(\.html)?([?#].*)?$/)
+ if (!match) return null
+ const [, base, uz, part, slug, html = '', rest = ''] = match
+ for (const [en, local] of pairs) {
+ const known = !en.endsWith('/') ? slug === '' : en === 'lessons/' ? slugs.has(slug) : /^module-\d\d$/.test(slug)
+ if (!known) continue
+ if (uz && part === en) return `${base}uz/${local}${slug}${html}${rest}`
+ if (!uz && part === local) return `${base}${en}${slug}${html}${rest}`
+ }
+ return null
+}
+
+export default {
+ extends: DefaultTheme,
+ // CodeEnhancer adds Run buttons to code blocks and Check editors to exercises;
+ // LabLink points each lesson at its module notebook in the Python Lab.
+ Layout: () => h(DefaultTheme.Layout, null, { 'doc-after': () => [h(CodeEnhancer), h(LabLink)] }),
+ enhanceApp({ app, router }) {
+ router.onBeforeRouteChange = href => { const target = localeTarget(href); if (target) { router.go(target); return false } }
+ app.component('PythonPlayground', Playground)
+ app.component('Difficulty', Difficulty)
+ app.component('Quiz', Quiz)
+ app.component('Yes', { render: () => h(Mark, { ok: true }) })
+ app.component('No', { render: () => h(Mark, { ok: false }) })
+ }
+}
diff --git a/docs/.vitepress/theme/style.css b/docs/.vitepress/theme/style.css
new file mode 100644
index 0000000..1df646b
--- /dev/null
+++ b/docs/.vitepress/theme/style.css
@@ -0,0 +1,108 @@
+/* Reserve the scrollbar's space so opening the search modal (which locks page scrolling)
+ doesn't shift the whole page sideways. No effect with macOS overlay scrollbars. */
+html{scrollbar-gutter:stable;background-color:var(--vp-c-bg)}
+:root{--vp-c-brand-1:#2563eb;--vp-c-brand-2:#1d4ed8;--vp-c-brand-3:#2563eb;--vp-c-brand-soft:rgba(37,99,235,.1);--vp-font-family-base:Inter,ui-sans-serif,system-ui,sans-serif;--vp-sidebar-width:280px}
+.dark{--vp-c-brand-1:#80aaff;--vp-c-brand-2:#aac6ff;--vp-c-brand-3:#2563eb}
+.VPDoc h1{letter-spacing:-.035em!important;font-size:36px!important}.vp-doc p,.vp-doc li{line-height:1.85}.VPNavBarTitle .title{font-weight:800;letter-spacing:-.03em}button:focus-visible,textarea:focus-visible{outline:3px solid var(--vp-c-brand-1);outline-offset:2px}.course-intro{border-left:4px solid var(--vp-c-brand-1);padding:12px 20px;background:var(--vp-c-brand-soft);margin:24px 0}@media(max-width:600px){.VPDoc h1{font-size:30px!important}}
+.difficulty{display:inline-flex;gap:1px;margin-left:.5em;font-size:.85em;line-height:1;vertical-align:.08em;font-family:system-ui,sans-serif;letter-spacing:0}.difficulty .on{color:var(--vp-c-brand-1)}.difficulty .off{color:var(--vp-c-text-3);opacity:.7}
+.mark{display:inline-flex;align-items:center;justify-content:center;width:1.4em;height:1.4em;border-radius:999px;vertical-align:-.22em}.mark svg{fill:none;stroke:currentColor;stroke-width:2.2;stroke-linecap:round;stroke-linejoin:round;width:.8em;height:.8em}.mark-yes{color:var(--vp-c-green-1);background:var(--vp-c-green-soft)}.mark-no{color:var(--vp-c-red-1);background:var(--vp-c-red-soft)}
+/* Code editor (CodeMirror) colors */
+:root{--cm-keyword:#8839ef;--cm-string:#328020;--cm-number:#b95001;--cm-comment:#6c6f81;--cm-function:#1e65f3;--cm-definition:#b8420f;--cm-builtin:#d20f39;--cm-operator:#5c5f77}
+.dark{--cm-keyword:#cba6f7;--cm-string:#a6e3a1;--cm-number:#fab387;--cm-comment:#9399b2;--cm-function:#89b4fa;--cm-definition:#f9e2af;--cm-builtin:#f38ba8;--cm-operator:#bac2de}
+/* Checkpoint quizzes */
+.VPSidebarItem .checkpoint-link{font-weight:600}
+.quiz-intro{font-size:16px}.quiz-best{color:var(--vp-c-text-2);font-size:14px}
+.vp-doc .quiz-questions{list-style:none;padding:0!important;counter-reset:q}
+.quiz-question{counter-increment:q;margin:24px 0!important;padding:18px 20px;border:1px solid var(--vp-c-divider);border-radius:12px;background:var(--vp-c-bg-soft)}
+.quiz-text{margin:0 0 10px!important;font-weight:600}.quiz-text::before{content:counter(q) ". "}
+.quiz-code{margin:8px 0 12px!important;padding:12px 16px!important;border-radius:8px;background:var(--vp-code-block-bg)!important;overflow-x:auto}
+.quiz-code code{font:14px/1.6 var(--vp-font-family-mono);white-space:pre;color:var(--vp-c-text-1)}
+.quiz-options{display:grid;gap:8px}
+.quiz-option{position:relative;display:flex;gap:10px;align-items:flex-start;text-align:left;padding:10px 12px;border:1px solid var(--vp-c-divider);border-radius:8px;background:var(--vp-c-bg);font-size:15px;white-space:pre-wrap;cursor:pointer}
+.quiz-option input{position:absolute;width:1px;height:1px;opacity:0;margin:0}
+.quiz-option:has(input:focus-visible){outline:3px solid var(--vp-c-brand-1);outline-offset:2px}
+.quiz-option input:focus-visible ~ .quiz-letter{outline:3px solid var(--vp-c-brand-1);outline-offset:2px}
+.quiz-option:has(input:disabled){cursor:default}
+.quiz-option:has(input:not(:disabled)):hover{border-color:var(--vp-c-brand-1)}
+.quiz-option.selected{border-color:var(--vp-c-brand-1);background:var(--vp-c-brand-soft)}
+.quiz-option.correct{border-color:var(--vp-c-green-1);background:var(--vp-c-green-soft)}
+.quiz-option.wrong{border-color:var(--vp-c-red-1);background:var(--vp-c-red-soft)}
+.quiz-letter{flex:none;width:22px;height:22px;display:inline-flex;align-items:center;justify-content:center;border-radius:999px;border:1px solid var(--vp-c-divider);font-size:12px;font-weight:700}
+.quiz-option-text{font-family:var(--vp-font-family-mono);font-size:14px}
+.quiz-feedback{margin-top:10px;font-size:14px;line-height:1.7}.quiz-feedback a{margin-left:6px}
+.quiz-actions{margin:24px 0;display:flex;gap:12px;align-items:center;flex-wrap:wrap}
+.quiz-submit{padding:10px 18px;border-radius:8px;font-weight:600;background:var(--vp-c-brand-1);color:#fff}
+.quiz-submit:disabled{opacity:.55;cursor:not-allowed}
+.quiz-result{font-size:16px;margin:0!important}
+.lab-footer{margin:32px 0 0!important;padding-top:16px;border-top:1px solid var(--vp-c-divider);font-size:14px}
+.quiz-review{margin:16px 0 0;font-size:14px;flex-basis:100%}
+.quiz-review ul{margin:6px 0 0;padding-left:20px}
+.lab-actions{margin:24px 0}.lab-button{display:inline-block;padding:10px 20px;border-radius:8px;background:var(--vp-c-brand-1);color:#fff!important;font-weight:600;text-decoration:none!important}.lab-button:hover{background:var(--vp-c-brand-2)}
+
+/* ---------- Python editor (playground, Run, exercises) ---------- */
+.python-editor{margin:16px 0;border:1px solid var(--vp-c-divider);border-radius:8px;overflow:hidden;background:var(--vp-code-block-bg)}
+.python-editor.is-exercise{border-color:var(--vp-c-brand-soft);box-shadow:0 0 0 1px var(--vp-c-brand-soft)}
+.editor-toolbar{display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap;padding:6px 8px 6px 16px;border-bottom:1px solid var(--vp-c-divider);background:var(--vp-c-bg-soft)}
+.editor-title{font:600 13px/1 var(--vp-font-family-mono);color:var(--vp-c-text-2)}
+.editor-buttons{display:flex;gap:6px;flex-wrap:wrap}
+.editor-buttons button{height:30px;padding:0 12px;border-radius:6px;font-size:13px;font-weight:600;color:var(--vp-c-text-2);border:1px solid transparent;transition:background .15s,color .15s,border-color .15s}
+.editor-buttons button:hover:not(:disabled){color:var(--vp-c-text-1);background:var(--vp-c-default-soft)}
+.editor-buttons button.is-active{color:var(--vp-c-brand-1);border-color:var(--vp-c-brand-soft)}
+.editor-buttons button.primary{color:#fff;background:var(--vp-c-brand-3)}
+.editor-buttons button.primary:hover:not(:disabled){color:#fff;background:var(--vp-c-brand-2)}
+.editor-buttons button:disabled{opacity:.6;cursor:default}
+.python-editor .code-editor .cm-editor{background:var(--vp-code-block-bg)}
+.editor-inputs{padding:10px 16px;border-top:1px solid var(--vp-c-divider);background:var(--vp-c-bg-soft);font-size:13px;color:var(--vp-c-text-2)}
+.editor-inputs textarea{display:block;width:100%;margin-top:6px;min-height:56px;padding:8px 12px;font:13px/1.6 var(--vp-font-family-mono);color:var(--vp-c-text-1);background:var(--vp-c-bg);border:1px solid var(--vp-c-divider);border-radius:6px;resize:vertical}
+.editor-verdict{margin:10px 12px 0;padding:8px 12px;border-radius:6px;font-size:14px}
+.editor-verdict.is-pass{background:var(--vp-c-green-soft);color:var(--vp-c-green-1)}
+.editor-verdict.is-fail{background:var(--vp-c-red-soft);color:var(--vp-c-red-1)}
+.editor-verdict.is-error{background:var(--vp-c-yellow-soft);color:var(--vp-c-yellow-1)}
+.editor-verdict.is-unknown{background:var(--vp-c-default-soft);color:var(--vp-c-text-2)}
+.verdict-icon{display:inline-flex;align-items:center;justify-content:center;width:1.4em;height:1.4em;border:2px solid currentColor;border-radius:999px;font:700 .75em/1 var(--vp-font-family-base);vertical-align:-.22em}
+.editor-verdict pre{margin:8px 0 4px;padding:8px 12px;background:var(--vp-c-bg);color:var(--vp-c-text-1);border-radius:6px;white-space:pre-wrap;font:13px/1.6 var(--vp-font-family-mono)}
+.editor-output{border-top:1px solid var(--vp-c-divider);background:var(--vp-c-bg)}
+.editor-output-label{padding:6px 16px 0;font:600 11px/1.6 var(--vp-font-family-base);letter-spacing:.04em;text-transform:uppercase;color:var(--vp-c-text-3)}
+.python-output{margin:0!important;padding:4px 16px 12px!important;max-height:340px;overflow:auto;white-space:pre-wrap;word-break:break-word;font:14px/1.7 var(--vp-font-family-mono);color:var(--vp-c-text-1);background:transparent!important;border-radius:0!important}
+.python-images{padding:12px;background:var(--vp-c-bg-soft);display:grid;gap:12px}
+.python-images img{display:block;max-width:100%;height:auto;margin:0 auto;border-radius:6px}
+.editor-hint{padding:6px 16px;border-top:1px solid var(--vp-c-divider);font-size:12px;color:var(--vp-c-text-3);background:var(--vp-c-bg-soft)}
+.editor-status{margin:0!important;padding:6px 16px 0;font-size:12px;color:var(--vp-c-text-2);background:var(--vp-c-bg-soft)}
+.editor-status:empty{display:none}
+.editor-keys{margin:0!important;padding:6px 16px;border-top:1px solid var(--vp-c-divider);font-size:11px;color:var(--vp-c-text-3);background:var(--vp-c-bg-soft)}
+/* Run bar attached under lesson code blocks */
+.vp-doc div.language-python.has-run-bar{margin-bottom:0;border-bottom-left-radius:0;border-bottom-right-radius:0}
+.code-run-bar{display:flex;justify-content:flex-end;align-items:center;margin:0 0 16px;padding:4px 8px;background:var(--vp-code-block-bg);border-top:1px solid var(--vp-c-divider);border-radius:0 0 8px 8px}
+.vp-doc .code-run-bar[hidden],.vp-doc div.language-python[hidden]{display:none!important}
+.code-run-bar button{height:26px;padding:0 10px;border-radius:6px;font-size:12px;font-weight:600;color:var(--vp-c-brand-1)}
+.code-run-bar button:hover{background:var(--vp-c-brand-soft)}
+.vp-doc details.details .code-run-bar{display:none}
+.vp-doc details.details div.language-python.has-run-bar{margin-bottom:16px;border-radius:8px}
+.exercise-bar{margin:12px 0 4px}
+.exercise-toggle{padding:6px 14px;font-size:14px;font-weight:600;border-radius:8px;border:1px solid var(--vp-c-brand-1);color:var(--vp-c-brand-1);background:var(--vp-c-brand-soft)}
+.exercise-toggle:hover{background:var(--vp-c-brand-1);color:#fff}
+/* On narrow screens VitePress code blocks go edge to edge; match that */
+@media (max-width:639px){
+ .vp-doc .python-editor,.vp-doc .code-run-bar{margin-left:-24px;margin-right:-24px;border-radius:0;border-left:0;border-right:0}
+ .vp-doc details.details .python-editor{margin-left:0;margin-right:0;border-radius:8px;border:1px solid var(--vp-c-divider)}
+}
+.python-editor.is-standalone .cm-scroller{min-height:220px}.python-editor.is-exercise .cm-scroller{min-height:150px}
+
+/* Lesson illustrations (light artwork: soften it in dark mode) */
+.vp-doc img.lesson-cover,
+.vp-doc img.lesson-diagram { display: block; width: 100%; height: auto; margin: 8px 0 24px; border: 1px solid var(--vp-c-divider); border-radius: 12px; }
+.dark .vp-doc img.lesson-cover,
+.dark .vp-doc img.lesson-diagram { filter: brightness(0.88); }
+
+/* Nav: the Python logo is wide (device plus wordmark), so keep it close to VitePress's default height. */
+.VPNavBarTitle .logo{height:40px;width:auto}
+/* Search: VitePress leaves #local-search content-sized, so the box is short. Let it fill the
+ space the nav already reserves, capped so it does not span the whole bar on wide screens. */
+@media (min-width: 768px){
+ .VPNavBarSearch #local-search{flex:1;max-width:280px}
+ /* The button is left-aligned, so the shortcut keys sit next to the label instead of at the end. */
+ .VPNavBarSearch .DocSearch-Button-Keys{margin-left:auto}
+}
+
+@media (max-width: 767px){.VPNavBarTitle .logo{height:32px}}
+
diff --git a/docs/checkpoints/module-01.md b/docs/checkpoints/module-01.md
new file mode 100644
index 0000000..12edf40
--- /dev/null
+++ b/docs/checkpoints/module-01.md
@@ -0,0 +1,9 @@
+---
+title: "Checkpoint: Getting Started"
+description: "Check your understanding of Getting Started with a short quiz."
+outline: false
+---
+
+# Checkpoint: Getting Started
+
+
diff --git a/docs/checkpoints/module-02.md b/docs/checkpoints/module-02.md
new file mode 100644
index 0000000..44af14f
--- /dev/null
+++ b/docs/checkpoints/module-02.md
@@ -0,0 +1,9 @@
+---
+title: "Checkpoint: Values and Variables"
+description: "Check your understanding of Values and Variables with a short quiz."
+outline: false
+---
+
+# Checkpoint: Values and Variables
+
+
diff --git a/docs/checkpoints/module-03.md b/docs/checkpoints/module-03.md
new file mode 100644
index 0000000..03198e2
--- /dev/null
+++ b/docs/checkpoints/module-03.md
@@ -0,0 +1,9 @@
+---
+title: "Checkpoint: Making Decisions"
+description: "Check your understanding of Making Decisions with a short quiz."
+outline: false
+---
+
+# Checkpoint: Making Decisions
+
+
diff --git a/docs/checkpoints/module-04.md b/docs/checkpoints/module-04.md
new file mode 100644
index 0000000..ba7ef24
--- /dev/null
+++ b/docs/checkpoints/module-04.md
@@ -0,0 +1,9 @@
+---
+title: "Checkpoint: Loops"
+description: "Check your understanding of Loops with a short quiz."
+outline: false
+---
+
+# Checkpoint: Loops
+
+
diff --git a/docs/checkpoints/module-05.md b/docs/checkpoints/module-05.md
new file mode 100644
index 0000000..102b921
--- /dev/null
+++ b/docs/checkpoints/module-05.md
@@ -0,0 +1,9 @@
+---
+title: "Checkpoint: Collections"
+description: "Check your understanding of Collections with a short quiz."
+outline: false
+---
+
+# Checkpoint: Collections
+
+
diff --git a/docs/checkpoints/module-06.md b/docs/checkpoints/module-06.md
new file mode 100644
index 0000000..1228dc1
--- /dev/null
+++ b/docs/checkpoints/module-06.md
@@ -0,0 +1,9 @@
+---
+title: "Checkpoint: Functions"
+description: "Check your understanding of Functions with a short quiz."
+outline: false
+---
+
+# Checkpoint: Functions
+
+
diff --git a/docs/checkpoints/module-07.md b/docs/checkpoints/module-07.md
new file mode 100644
index 0000000..1408f6d
--- /dev/null
+++ b/docs/checkpoints/module-07.md
@@ -0,0 +1,9 @@
+---
+title: "Checkpoint: Modules and the Standard Library"
+description: "Check your understanding of Modules and the Standard Library with a short quiz."
+outline: false
+---
+
+# Checkpoint: Modules and the Standard Library
+
+
diff --git a/docs/checkpoints/module-08.md b/docs/checkpoints/module-08.md
new file mode 100644
index 0000000..82bd180
--- /dev/null
+++ b/docs/checkpoints/module-08.md
@@ -0,0 +1,9 @@
+---
+title: "Checkpoint: Errors and Files"
+description: "Check your understanding of Errors and Files with a short quiz."
+outline: false
+---
+
+# Checkpoint: Errors and Files
+
+
diff --git a/docs/checkpoints/module-09.md b/docs/checkpoints/module-09.md
new file mode 100644
index 0000000..cb27141
--- /dev/null
+++ b/docs/checkpoints/module-09.md
@@ -0,0 +1,9 @@
+---
+title: "Checkpoint: Classes and Objects"
+description: "Check your understanding of Classes and Objects with a short quiz."
+outline: false
+---
+
+# Checkpoint: Classes and Objects
+
+
diff --git a/docs/checkpoints/module-10.md b/docs/checkpoints/module-10.md
new file mode 100644
index 0000000..6b26eac
--- /dev/null
+++ b/docs/checkpoints/module-10.md
@@ -0,0 +1,9 @@
+---
+title: "Checkpoint: Object-Oriented Design"
+description: "Check your understanding of Object-Oriented Design with a short quiz."
+outline: false
+---
+
+# Checkpoint: Object-Oriented Design
+
+
diff --git a/docs/checkpoints/module-11.md b/docs/checkpoints/module-11.md
new file mode 100644
index 0000000..1e4eb5e
--- /dev/null
+++ b/docs/checkpoints/module-11.md
@@ -0,0 +1,9 @@
+---
+title: "Checkpoint: Testing and Debugging"
+description: "Check your understanding of Testing and Debugging with a short quiz."
+outline: false
+---
+
+# Checkpoint: Testing and Debugging
+
+
diff --git a/docs/checkpoints/module-12.md b/docs/checkpoints/module-12.md
new file mode 100644
index 0000000..7995711
--- /dev/null
+++ b/docs/checkpoints/module-12.md
@@ -0,0 +1,9 @@
+---
+title: "Checkpoint: Going Further"
+description: "Check your understanding of Going Further with a short quiz."
+outline: false
+---
+
+# Checkpoint: Going Further
+
+
diff --git a/docs/checkpoints/module-13.md b/docs/checkpoints/module-13.md
new file mode 100644
index 0000000..5fcde32
--- /dev/null
+++ b/docs/checkpoints/module-13.md
@@ -0,0 +1,9 @@
+---
+title: "Checkpoint: Working with Data"
+description: "Check your understanding of Working with Data (Optional) with a short quiz."
+outline: false
+---
+
+# Checkpoint: Working with Data
+
+
diff --git a/docs/checkpoints/module-14.md b/docs/checkpoints/module-14.md
new file mode 100644
index 0000000..ee39a04
--- /dev/null
+++ b/docs/checkpoints/module-14.md
@@ -0,0 +1,9 @@
+---
+title: "Checkpoint: Advanced Python"
+description: "Check your understanding of Advanced Python with a short quiz."
+outline: false
+---
+
+# Checkpoint: Advanced Python
+
+
diff --git a/docs/index.md b/docs/index.md
new file mode 100644
index 0000000..ec9a255
--- /dev/null
+++ b/docs/index.md
@@ -0,0 +1,41 @@
+---
+title: Learn Python
+description: "A free Python course for beginners: clear explanations, code you can run in the browser, and exercises with solutions."
+---
+
+# Learn Python
+
+Start from zero. Write code, run it right on the page, and build real skills one lesson at a time.
+
+This course is for people who are new to programming, or new to Python. Every lesson explains one idea with short examples, shows the mistakes beginners usually make, and ends with exercises you can check yourself. You don't need to install anything to begin: examples run in your browser.
+
+**[Start learning →](/lessons/what-is-python)** · [Open the playground](/playground) · [Özbekça versiya](/uz/)
+
+
+## Learning path
+
+| Part | Modules | You'll be able to |
+| --- | --- | --- |
+| **1 · Foundations** | Getting started · Values and variables · Decisions · Loops · Collections · Functions | Write small programs that make decisions, repeat work, and organize data |
+| **2 · Writing real programs** | Modules and the standard library · Errors and files · Classes and objects · Object-oriented design · Testing and debugging · Going further · Working with data (optional) | Read and write files, handle errors, design classes, test your code, and analyze data |
+| **3 · Advanced Python** (optional) | Closures and decorators · The data model · Context managers · Async · Memory and performance · Design patterns · Threads and processes · Testing in depth · Log pipeline project | Understand how the language works underneath and write idiomatic, fast, well-tested Python |
+
+## Practice built in
+
+- **Run every example.** Each code block has a **Run** button that opens it in an editor right on the page.
+- **Check your exercises.** Under each exercise, **Solve in the browser** opens an editor with a **Check** button that compares your output with the expected output.
+- **Build projects.** Seven guided projects: a number guessing game, a quiz game, an expense tracker, a library management system, a text analyzer, a sales data report, and a log pipeline.
+- **Test yourself.** Every module ends with a short **checkpoint quiz**.
+- **Experiment freely.** Use the [Playground](/playground) for quick code, or the [Python Lab](/lab) for notebooks with practice exercises for every module.
+
+## How to use this course
+
+1. **Go in order.** Each lesson builds on the ones before it.
+2. **Predict, then run.** Before running an example, guess the output.
+3. **Break things on purpose.** Change a value or delete a line and see what happens.
+4. **Try exercises before opening solutions.** Stars show difficulty: easy, medium, hard.
+5. **Take the checkpoint quiz** at the end of each module. Your best score is saved in your browser, with no account needed.
+
+## What you need
+
+A modern browser and some practice time. The first run of a code example downloads Python into your browser, so it needs an internet connection. Examples target **Python 3.14**.
diff --git a/docs/lab.md b/docs/lab.md
new file mode 100644
index 0000000..a6fe1ce
--- /dev/null
+++ b/docs/lab.md
@@ -0,0 +1,47 @@
+---
+title: Python Lab
+description: "A full Jupyter notebook environment in your browser, with practice notebooks for every module."
+---
+
+# Python Lab
+
+The Python Lab is a complete **notebook environment** that runs entirely in your browser. It uses [JupyterLite](https://jupyterlite.readthedocs.io/) with a Python kernel powered by Pyodide, so there is nothing to install.
+
+
+
+[Open the Python Lab](/lab/lab/index.html?path=00-start-here.ipynb){.lab-button target="_blank" rel="noopener"}
+
+
+
+## What's inside
+
+- **00-start-here.ipynb**: a short introduction to notebooks.
+- **One practice notebook per module**: every exercise from the lessons, in English and Uzbek, each with an empty code cell for your answer. Solutions stay in the lessons, so try first and check afterwards.
+- A file browser, so you can create your own notebooks, text files, and CSV files.
+
+## Playground or Lab?
+
+| | Playground and lesson editors | Python Lab |
+|---|---|---|
+| Best for | Running one example or checking an exercise | Longer practice sessions and experiments |
+| Code runs | The whole editor, top to bottom | Cell by cell, keeping variables between cells |
+| Files | Temporary | Saved in your browser, can be downloaded |
+| Opens | Right on the page | In a new tab |
+
+## Using notebooks
+
+1. Open a notebook from the file browser on the left.
+2. Click a code cell, write your code, and press **Shift + Enter** to run it.
+3. Variables stay available in later cells, so run cells **in order** from the top.
+4. If things get confusing, use **Kernel → Restart Kernel and Clear Outputs** and run again from the top.
+
+::: warning Keep your work
+Notebooks are stored in **this browser only**. Clearing site data or switching browsers removes them. Use **File → Download** to save important notebooks to your computer.
+:::
+
+## Limits
+
+- The first start downloads Python, which can take a little while.
+- Packages that Pyodide supports (like numpy, pandas, and matplotlib) work. Many others don't.
+- Network access from Python code is limited by browser security rules.
+- For big projects, install Python on your computer (see *Installing Python*).
diff --git a/docs/lessons/01-getting-started/01-what-is-python.md b/docs/lessons/01-getting-started/01-what-is-python.md
new file mode 100644
index 0000000..bcdcb09
--- /dev/null
+++ b/docs/lessons/01-getting-started/01-what-is-python.md
@@ -0,0 +1,257 @@
+---
+title: What Is Python?
+description: "What Python is, what people build with it, how it runs your code, and why it's a great first programming language."
+---
+
+# What Is Python?
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- What a programming language is and where Python fits
+- What people build with Python
+- How Python runs your code
+- Why Python is a good first language, and what it's less suited for
+- How to run your very first line of Python, right on this page
+:::
+
+## Why it matters
+
+A computer does exactly what it's told, nothing more. A **programming language** is a way to write those instructions so that both people and computers can understand them. Python is one of the most widely used programming languages in the world. It powers websites, scientific research, and AI tools, and people also use it for small scripts that save a few hours of boring work every week.
+
+Learning Python first gives you a language you can keep using long after this course.
+
+## A programming language in one example
+
+Here is a complete Python program:
+
+```python
+print("Hello! I'm learning Python.")
+```
+
+Output:
+
+```text
+Hello! I'm learning Python.
+```
+
+`print` is a built-in **function**: a named action Python already knows. The text inside quotes is the value you give it. You'll learn exactly how this works in the next few lessons. For now, notice how little there is to it: no setup code and no punctuation you have to memorize.
+
+A slightly bigger program still reads almost like English:
+
+```python
+prices = [1.20, 2.50, 0.99]
+total = sum(prices)
+
+if total > 4:
+ print("That's more than 4 dollars.")
+else:
+ print("Under 4 dollars.")
+```
+
+Even without knowing Python, you can probably guess what this does. That readability is Python's biggest strength. (The square-bracket list and `if`/`else` get their own lessons later, so don't worry about the details yet.)
+
+## A short history
+
+- **Guido van Rossum** started working on Python in the late 1980s and released it in **1991**.
+- The name comes from the British comedy show *Monty Python's Flying Circus*, not the snake.
+- **Python 3** came out in 2008 and fixed long-standing design problems. It wasn't fully compatible with Python 2.
+- **Python 2** reached end of life on January 1, 2020. Everything you learn here is Python 3.
+- Python is free and open source. It's developed by an open community of core developers and contributors, and the **Python Software Foundation** looks after it.
+- A new version comes out **every October**: 3.13 in 2024, 3.14 in 2025, and so on. Each version gets fixes and security updates for about five years.
+
+::: warning Old tutorials
+If you see code like `print "hello"` (with no parentheses), it's Python 2. It won't run in Python 3. See **Common mistakes** below.
+:::
+
+## What people build with Python
+
+| Area | Examples | Popular tools |
+|---|---|---|
+| **Automation and scripting** | Renaming 1,000 files, filling spreadsheets, sending reports | Standard library |
+| **Data analysis** | Cleaning data, statistics, charts | pandas, NumPy, Matplotlib |
+| **Machine learning and AI** | Image recognition, language models, recommendations | PyTorch, scikit-learn |
+| **Web development** | Websites and APIs | Django, Flask, FastAPI |
+| **Science and education** | Simulations, research code, teaching programming | Jupyter notebooks, SciPy |
+| **Testing and DevOps** | Test suites, deployment scripts, server tools | pytest, Ansible |
+
+You don't need any of those tools yet. This course teaches the core language and the **standard library**, the large set of modules that comes with every Python install. Every tool in the table is built on top of that.
+
+## How Python runs your code
+
+You write Python code as plain text, usually in a file ending in `.py`. A program called the **Python interpreter** reads that text and carries out the instructions:
+
+1. **Read** your source code, e.g. `hello.py`.
+2. **Check and translate** it into a simpler internal form called *bytecode*. If there's a syntax mistake, Python stops here and tells you where.
+3. **Run** the bytecode one instruction at a time. If something goes wrong while running, Python shows an error message called a *traceback*.
+
+This all happens in a fraction of a second when you run a program. Two things follow from it:
+
+- **You get feedback fast.** Edit, run, see the result, repeat. You don't have to build or compile anything separately.
+- **Errors show up when the line runs.** Python checks the grammar of the whole file first, but a misspelled name on line 50 is only caught when line 50 actually runs.
+
+The standard interpreter is called **CPython** (it's written in C). It's what you'll install in the next lesson. The code runner on this site uses **Pyodide**, a version of CPython that runs inside your web browser.
+
+## Why Python is a good first language
+
+- **Readable.** Code blocks are marked by indentation, not curly braces, so programs look clean and similar to each other.
+- **Quick to start.** One line is a complete program.
+- **"Batteries included."** Files, dates, math, random numbers, JSON, and much more are built in.
+- **Huge community.** Almost any question you have has already been answered, and there are libraries for almost anything.
+- **It grows with you.** The same language is used by beginners and by large companies.
+
+Python has trade-offs too:
+
+- **Speed.** Pure Python is slower than languages like C, Rust, or Go. In practice, the heavy lifting in libraries like NumPy is done in fast compiled code, so this rarely matters when you're learning.
+- **Mobile apps and browser front ends** are usually built with other languages (Swift, Kotlin, JavaScript).
+- **Types are checked at run time.** Python won't stop you from mixing up a number and a text value until that line runs. Tests and type hints, which come later in the course, help with this.
+
+## Try it
+
+This editor runs real Python in your browser. Press **▶ Run** and see the output. Then change the text, add a second `print` line, and run it again.
+
+
+
+Python has a small hidden poem about good code design. Run this:
+
+```python
+import this
+```
+
+You'll see *The Zen of Python*, 19 short lines that describe how Python code is meant to feel. "Readability counts." is one of them.
+
+## Common mistakes
+
+### 1. Following a Python 2 tutorial
+
+```py
+print "hello"
+```
+
+```text
+SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?
+```
+
+**Fix:** in Python 3, `print` is a function and always needs parentheses: `print("hello")`. If a tutorial uses the old style, find a newer one.
+
+### 2. Changing capitalization
+
+```py
+Print("hi")
+```
+
+```text
+NameError: name 'Print' is not defined. Did you mean: 'print'?
+```
+
+Python is **case-sensitive**: `print`, `Print`, and `PRINT` are three different names. Only `print` exists.
+
+### 3. Forgetting a closing quote
+
+```py
+print("Hi)
+```
+
+```text
+SyntaxError: unterminated string literal (detected at line 1)
+```
+
+Text values need a quote at **both** ends: `"Hi"`.
+
+::: info Error messages are your friends
+Every error above tells you *what* went wrong and often suggests a fix. Read the **last line** of an error message first. You'll learn to read the full message in the *Reading Errors and Debugging* lesson.
+:::
+
+## Practice
+
+### 1. Your first message
+
+In the editor above, make Python print your name and the city you live in, on two separate lines.
+
+::: details Solution
+```python
+print("My name is Aziza.")
+print("I live in Tashkent.")
+```
+
+Each `print` call puts its output on a new line.
+:::
+
+### 2. Predict, then run
+
+Before you run it, write down what you think this prints. Then run it and compare.
+
+```python
+print("5 + 5")
+print(5 + 5)
+```
+
+::: details Solution
+```text
+5 + 5
+10
+```
+
+With quotes, `"5 + 5"` is just **text**, printed as it is. Without quotes, `5 + 5` is a **calculation**, so Python prints the result. This difference between text and numbers comes up all the time.
+:::
+
+### 3. Fix the program
+
+This program has three mistakes. Fix it so it runs and prints two lines.
+
+```py
+Print("Python was released in 1991)
+print "It is named after Monty Python."
+```
+
+::: details Solution
+```python
+print("Python was released in 1991")
+print("It is named after Monty Python.")
+```
+
+1. `Print` → `print` (capitalization)
+2. The closing `"` was missing after `1991`
+3. `print` needs parentheses (the Python 2 style doesn't work)
+:::
+
+### 4. Explore the Zen
+
+Run `import this`. Find the line about how many ways there should be to do something, and the line about errors. Write each one down, then explain one of them in your own words.
+
+::: details Solution
+- *"There should be one-- and preferably only one --obvious way to do it."*
+- *"Errors should never pass silently."*
+
+For example, the second one means a program shouldn't quietly ignore problems. It's better to stop with a clear error than to keep going with wrong data.
+:::
+
+### 5. Let Python do the math
+
+How many minutes are there in a week? Don't work it out yourself. Print a line that shows a label and lets Python calculate the number from 7 days, 24 hours and 60 minutes. Use the second line in the **Try it** editor as a model.
+
+::: details Solution
+```python
+print("Minutes in a week:", 7 * 24 * 60)
+```
+
+```text
+Minutes in a week: 10080
+```
+
+The label is text in quotes, so it prints as it is. The calculation has no quotes, so Python works it out first. `*` means multiply.
+:::
+
+## Recap
+
+- A programming language is a precise way to give instructions to a computer. Python is known for being readable.
+- Python was created by Guido van Rossum and released in 1991. Always use **Python 3**.
+- People use Python for automation, data, AI, the web, science, and education.
+- The **interpreter** reads your `.py` file, translates it, and runs it, so you can edit, run, and repeat quickly.
+- Python is case-sensitive, and error messages usually point you to the fix.
+
+## Further reading
+
+- [The Python Tutorial - Whetting Your Appetite](https://docs.python.org/3/tutorial/appetite.html)
+- [Python FAQ - General](https://docs.python.org/3/faq/general.html)
+- [Python release status and support dates](https://devguide.python.org/versions/)
diff --git a/docs/lessons/01-getting-started/02-install-and-setup.md b/docs/lessons/01-getting-started/02-install-and-setup.md
new file mode 100644
index 0000000..c121f4b
--- /dev/null
+++ b/docs/lessons/01-getting-started/02-install-and-setup.md
@@ -0,0 +1,299 @@
+---
+title: Installing Python
+description: "Install Python 3 on Windows, macOS, or Linux, check that it works, and choose a code editor."
+---
+
+# Installing Python
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- Whether you need to install anything yet
+- How to install Python on **Windows**, **macOS**, or **Linux**
+- How to check which version you have
+- How to open Python's interactive prompt, and how to leave it
+- Which code editor to pick
+:::
+
+## Why it matters
+
+The editor on these pages is perfect for learning, but real programs live in files on your computer. They read your spreadsheets, rename your photos, and keep running long after you close the browser. For that you need Python installed, plus a code editor to write in.
+
+### Do you need to install it right now?
+
+**Not yet.** Every example in the early lessons runs in your browser, on the lesson page or in the [Playground](/playground). You can skip this lesson for now and come back later.
+
+Install Python on your computer when you want to:
+
+- write programs that are saved as files on your computer,
+- work with real files and folders,
+- run programs that take longer than a few seconds,
+- follow along with later lessons in your own editor.
+
+## Which version?
+
+Install the **latest Python 3 release** from [python.org](https://www.python.org/downloads/). This course targets **Python 3.14**. Almost every example also works on 3.10 or newer, so a slightly older Python that's already on your computer is fine to start with.
+
+::: warning Not Python 2
+Never install Python 2 for this course. It's been unsupported since 2020.
+:::
+
+## Windows
+
+Windows now has an official tool called the **Python Install Manager**. It installs Python and keeps it up to date.
+
+1. Install **Python Install Manager** in one of these two ways:
+ - Open the **Microsoft Store**, search for **Python Install Manager**, and click **Install**, or
+ - download it from [python.org/downloads](https://www.python.org/downloads/) and run it.
+2. Open **Terminal** (or **PowerShell**) from the Start menu.
+3. Install the latest Python:
+
+ ```text
+ py install 3.14
+ ```
+
+4. It may ask whether to add a folder to your **PATH** (the list of folders Windows searches for commands). This is optional. The `python` and `py` commands already work through Windows **app execution aliases**. Saying **yes** adds `%LocalAppData%\Python\bin`, which also gives you versioned commands such as `python3.14`.
+5. Check it worked:
+
+ ```text
+ python --version
+ ```
+
+ You should see something like `Python 3.14.7`. The last number changes with each bug-fix release.
+
+Useful commands:
+
+| Command | What it does |
+|---|---|
+| `py list` | Show installed Python versions |
+| `py install 3.14` | Install a version |
+| `py` or `python` | Start the default Python |
+| `py help` | Show all commands |
+
+::: details The older ".exe" installer
+You may see tutorials that use the classic `python-3.x.x-amd64.exe` installer, where you must tick **"Add python.exe to PATH"**. It still works for 3.14, but it's deprecated and won't be produced for Python 3.16 or later. Use the Install Manager instead.
+:::
+
+## macOS
+
+macOS doesn't come with an up-to-date Python you should use.
+
+1. Go to [python.org/downloads](https://www.python.org/downloads/) and download the **macOS installer** (a `.pkg` file). It works on both Apple Silicon and Intel Macs.
+2. Open the file and follow the steps.
+3. When it finishes, a Finder window opens. Double-click **Install Certificates.command**. This lets Python make secure (HTTPS) connections.
+4. Open **Terminal** (press ⌘ + Space and type *Terminal*) and check:
+
+ ```text
+ python3 --version
+ ```
+
+On macOS, the command is **`python3`**, not `python`. When a lesson says `python`, type `python3`.
+
+::: details Using Homebrew instead
+If you already use [Homebrew](https://brew.sh), `brew install python` works too. If you don't know what Homebrew is, use the python.org installer.
+:::
+
+## Linux
+
+Most Linux systems already have Python 3. Open a terminal and check:
+
+```text
+python3 --version
+```
+
+If it's missing, install it with your package manager:
+
+| Distribution | Command |
+|---|---|
+| Ubuntu, Debian, Mint | `sudo apt install python3` |
+| Fedora | `sudo dnf install python3` |
+| Arch | `sudo pacman -S python` |
+
+Your distribution's version may be a little older than 3.14. That's fine for learning. Don't remove or replace the system Python, because parts of the operating system depend on it.
+
+## Check that it works: the interactive prompt
+
+Type `python` (Windows) or `python3` (macOS and Linux) with nothing after it, and press Enter:
+
+```text
+Python 3.14.7 (main, ...) on darwin
+Type "help", "copyright", "credits" or "license" for more information.
+>>>
+```
+
+The `>>>` is the **interactive prompt**, also called the **REPL**. You type one line of Python, press Enter, and see the result right away. Try it:
+
+```text
+>>> 2 + 3
+5
+>>> print("It works!")
+It works!
+```
+
+To leave, type `exit` and press Enter (on Python 3.12 and older, type `exit()`), or press **Ctrl + D** (macOS and Linux) or **Ctrl + Z, then Enter** (Windows).
+
+You'll use the REPL and learn to run `.py` files in the next lesson.
+
+## Choosing a code editor
+
+You can write Python in any plain-text editor, but a code editor colors your code, catches mistakes early, and runs programs with one click.
+
+| Editor | Good for | Notes |
+|---|---|---|
+| **[Visual Studio Code](https://code.visualstudio.com/)** | Most learners | Free. Install the **Python** extension from Microsoft. It's the most widely used choice. |
+| **[Thonny](https://thonny.org/)** | Absolute beginners | Free and very simple, with a built-in step-by-step debugger. It can come with Python bundled. |
+| **IDLE** | Quick start with nothing extra | Comes with Python from python.org. It's basic but works right away. |
+| **[PyCharm](https://www.jetbrains.com/pycharm/)** | Larger projects later | Powerful, but has more to learn. |
+
+**Recommendation:** if you're unsure, use **VS Code** with the Python extension. If it feels overwhelming, start with **Thonny**.
+
+::: tip VS Code: pick the right Python
+If you have more than one Python on your computer, VS Code may run your file with the wrong one. Open the Command Palette (**Ctrl + Shift + P**, or **⌘ + Shift + P** on macOS), run **Python: Select Interpreter**, and choose the version you installed. The chosen version is shown in the status bar at the bottom right when a `.py` file is open. Click it to change it again.
+:::
+
+## Which Python is running?
+
+This short program prints the version and location of the Python that runs it. Try it on the page, then save it as a file on your computer and run it there too:
+
+```python
+import sys
+
+print("Version:", sys.version.split()[0])
+print("Location:", sys.executable)
+```
+
+On the page, you'll see the version of the in-browser Python (Pyodide). On your computer, you'll see your installed version and where it lives on disk.
+
+## Common mistakes
+
+### 1. "python is not recognized", or the Store opens (Windows)
+
+```text
+'python' is not recognized as an internal or external command,
+operable program or batch file.
+```
+
+Windows can't find the `python` command. On some computers, typing `python` opens the Microsoft Store instead, because Windows has placeholder shortcuts. **Fix:**
+- Make sure you installed the **Python Install Manager** (see above).
+- Open Start → **Manage app execution aliases** and check that the **Python (default)** aliases are turned on. If they already are, turn them off and on again to refresh them. If the Store still opens, turn off the **python.exe** and **python3.exe** entries that belong to *App Installer*.
+- Close and reopen the terminal. Changes only apply to new windows.
+- Still stuck? Check that your PATH contains `%UserProfile%\AppData\Local\Microsoft\WindowsApps`. Windows adds it by default, and the aliases stop working if it's removed.
+
+### 2. `command not found: python` (macOS or Linux)
+
+```text
+% python --version
+zsh: command not found: python
+```
+
+On Linux the shell usually says `bash: python: command not found`. **Fix:** use **`python3`**. On these systems, `python` often doesn't exist, or it's an old Python 2.
+
+### 3. Typing terminal commands inside Python
+
+```py
+>>> python hello.py
+```
+
+```text
+SyntaxError: invalid syntax
+```
+
+At the `>>>` prompt you're **inside** Python, and `python hello.py` isn't Python code. **Fix:** leave with `exit`, then run the command in the normal terminal. The prompt tells you where you are:
+
+| Prompt | You are in… | Type |
+|---|---|---|
+| `>>>` | Python (REPL) | Python code, e.g. `print("hi")` |
+| `$`, `%`, or `PS C:\>` | Terminal / shell | Commands, e.g. `python hello.py` |
+
+## Practice
+
+### 1. Check your version
+
+Install Python (or find the one you have) and run the version command. Write down the exact version number.
+
+::: details Solution
+- **Windows:** `python --version` (or `py --version`)
+- **macOS / Linux:** `python3 --version`
+
+Output looks like `Python 3.14.7`. The first two numbers (`3.14`) are the version that matters.
+:::
+
+### 2. REPL calculator
+
+Open the interactive prompt and use it to calculate:
+1. `365 * 24` (hours in a year)
+2. `2 ** 10` (`**` means "to the power of")
+
+Then leave the prompt.
+
+::: details Solution
+```text
+>>> 365 * 24
+8760
+>>> 2 ** 10
+1024
+>>> exit
+```
+
+In the REPL you don't need `print()` to see a result. It shows the value of each expression automatically. This only happens in the REPL, not in `.py` files.
+:::
+
+### 3. Where are you?
+
+For each line, decide whether it should be typed at the **terminal prompt** or the **Python `>>>` prompt**:
+
+1. `python3 --version`
+2. `print("hello")`
+3. `py list`
+4. `10 / 4`
+
+::: details Solution
+1. Terminal: it runs the `python3` program.
+2. Python: it's Python code.
+3. Terminal: it's a Python Install Manager command (Windows).
+4. Python: it's a Python expression, and the result is `2.5`.
+:::
+
+### 4. Two Pythons
+
+Run the **Which Python is running?** program on this page, then save it as `which_python.py` on your computer and run it with `python which_python.py` (or `python3 which_python.py`). Compare the two outputs. Why are they different?
+
+::: details Solution
+The browser version runs **Pyodide**, so its location is a virtual path inside the browser. Your computer runs the Python you installed, so the location is a real folder, for example `C:\Users\you\AppData\Local\Python\...` or `/Library/Frameworks/Python.framework/...`. The version numbers may differ too. Different Pythons can be installed side by side, and `sys.executable` tells you which one is running your code.
+:::
+
+### 5. Fix the session
+
+A learner on a Mac typed these lines and got two errors. For each error, say what went wrong and what they should type instead.
+
+```text
+% python --version
+zsh: command not found: python
+% python3
+>>> python3 hello.py
+SyntaxError: invalid syntax
+```
+
+::: details Solution
+1. On macOS the command is `python3`, so type `python3 --version`.
+2. `python3` worked and opened the REPL. Then `python3 hello.py` was typed at the `>>>` prompt, where only Python code works. Leave with `exit`, then type `python3 hello.py` at the `%` terminal prompt.
+
+The prompt at the start of the line (`%` or `>>>`) tells you whether you're in the terminal or inside Python.
+:::
+
+## Recap
+
+- Early lessons run in the browser, so install Python when you want to work with files on your own computer.
+- **Windows:** Python Install Manager → `py install 3.14` → check with `python --version`.
+- **macOS:** python.org installer → check with `python3 --version`.
+- **Linux:** usually already installed → `python3 --version`. Don't replace the system Python.
+- `>>>` means you're inside Python. Leave with `exit`.
+- Pick an editor: **VS Code** with the Python extension, or **Thonny** for a gentler start.
+
+## Further reading
+
+- [Python downloads](https://www.python.org/downloads/)
+- [Using Python on Windows](https://docs.python.org/3/using/windows.html)
+- [Using Python on macOS](https://docs.python.org/3/using/mac.html)
+- [Using Python on Unix platforms](https://docs.python.org/3/using/unix.html)
+- [Python in Visual Studio Code](https://code.visualstudio.com/docs/python/python-tutorial)
diff --git a/docs/lessons/01-getting-started/03-running-python.md b/docs/lessons/01-getting-started/03-running-python.md
new file mode 100644
index 0000000..c14066f
--- /dev/null
+++ b/docs/lessons/01-getting-started/03-running-python.md
@@ -0,0 +1,317 @@
+---
+title: Running Python Code
+description: "The three ways to run Python: the interactive prompt (REPL), script files, and your editor, and when to use each."
+---
+
+# Running Python Code
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- The difference between the **interactive prompt** and a **script file**
+- How to create a `.py` file and run it from the terminal
+- How to run a file from your code editor
+- Why the terminal's **current folder** matters
+- Which way to use for which job
+:::
+
+## Why it matters
+
+You'll run code hundreds of times while learning. Knowing *where* your code runs, and what each way shows you, saves you from confusing moments like "my program printed nothing" or "Python can't find my file".
+
+There are three common ways to run Python:
+
+| Way | What it is | Best for |
+|---|---|---|
+| **Interactive prompt (REPL)** | Type one line, see the result immediately | Quick experiments, checking an idea |
+| **Script file** | Save code in a `.py` file and run the whole file | Real programs you want to keep |
+| **In the browser** | The editor on these lesson pages | Following the lessons, no install |
+
+Your code editor is really a comfortable way to do the second one: it saves a file and runs it for you.
+
+## 1. The interactive prompt (REPL)
+
+REPL stands for **Read-Eval-Print Loop**: Python **reads** a line, **evaluates** it, **prints** the result, and **loops** back to wait for the next line.
+
+Start it by typing `python` (Windows) or `python3` (macOS and Linux) in a terminal:
+
+```text
+>>> 7 * 6
+42
+>>> name = "Aziza"
+>>> name
+'Aziza'
+>>> print("Hi,", name)
+Hi, Aziza
+```
+
+A few things to notice:
+
+- In the REPL, typing a value on its own (`7 * 6`, `name`) **shows it automatically**. You don't need `print()`.
+- Variables stay alive until you leave. `name` was still there on the next line.
+- For code that spans several lines, like an `if`, the prompt changes to `...` so you can keep typing. Press Enter on an empty line to finish.
+
+```text
+>>> if 7 > 5:
+... print("seven is bigger")
+...
+seven is bigger
+```
+
+Recent Python versions (3.13 and newer) have a colored prompt and let you edit whole blocks with the arrow keys. Python 3.14 also highlights your code in color as you type. Press **↑** to bring back earlier lines.
+
+**Leave** with `exit` (or `exit()` on older versions), or press **Ctrl + D** (macOS and Linux) or **Ctrl + Z, then Enter** (Windows). Everything you typed is gone when you leave. The REPL is a scratchpad, not a place to keep work.
+
+::: info Get help without leaving
+`help(print)` shows documentation for `print`. Press `q` to close it. `dir("text")` lists everything you can do with a string. Skip the names that start with underscores for now.
+:::
+
+## 2. Script files
+
+A **script** is a plain-text file with a `.py` extension that holds a whole program. Python runs it **top to bottom, once**, then exits.
+
+### Step 1: create a folder and a file
+
+Make a folder for your course work, for example `python-course` in your Documents. In your editor, create a new file in it named **`hello.py`** with this content:
+
+```python
+print("Hello from a file!")
+print("This line runs second.")
+print("And this one runs last.")
+```
+
+Save the file.
+
+Give files short, descriptive names like `hello.py` or `dice_game.py`. Avoid names of Python's own modules, such as `random.py` or `math.py`. Later, when you `import random`, Python would load your file instead of its own module.
+
+### Step 2: open a terminal in that folder
+
+The terminal always works *inside* one folder, called the **current folder** (or *working directory*). Use `cd` ("change directory") to move there:
+
+```text
+cd Documents/python-course
+```
+
+Check you're in the right place by listing the files. Use `dir` on Windows or `ls` on macOS and Linux. You should see `hello.py`.
+
+::: tip Shortcut
+In VS Code, choose **Terminal → New Terminal**. It opens already inside your project folder.
+:::
+
+### Step 3: run it
+
+```text
+python hello.py
+```
+
+(On macOS and Linux, use `python3 hello.py`. On Windows, `py hello.py` also works.)
+
+```text
+Hello from a file!
+This line runs second.
+And this one runs last.
+```
+
+Change the file, save it, and run the same command again. That's the loop you'll use all the time: **edit → save → run**.
+
+### Scripts don't show values automatically
+
+This is the most common surprise when moving from the REPL to files. Save this as `values.py` and run it:
+
+```python
+x = 5
+x * 2
+print(x * 2)
+```
+
+```text
+10
+```
+
+Only **one** line of output appears. The line `x * 2` is calculated and then thrown away. In a script, you only see what you `print()`.
+
+## 3. Running from your editor
+
+Editors can run the current file for you:
+
+- **VS Code** (with the Python extension): click the **▶ Run Python File** button in the top-right corner. The output appears in the terminal panel at the bottom.
+- **Thonny:** press **F5** or click the green **Run** button.
+- **IDLE:** open the file, then press **F5** (*Run → Run Module*).
+
+Behind the scenes, the editor runs `python yourfile.py` for you. If something doesn't work, running the command yourself in a terminal shows you exactly what's happening.
+
+## 4. In the browser
+
+The editors on these pages run **Pyodide**, real Python compiled to run inside your browser. They work like a small script file:
+
+- The whole box runs top to bottom when you press **▶ Run**.
+- You only see what you `print()`.
+- Each run starts fresh, so variables from the previous run are gone.
+
+
+
+## Which one should I use?
+
+| I want to… | Use |
+|---|---|
+| Check what `10 / 3` gives | REPL (or the browser) |
+| Try a string method I just read about | REPL |
+| Write a program I'll run again tomorrow | Script file |
+| Do this course's examples and exercises | Browser, or a script file |
+| Share code with someone | Script file |
+
+A common habit is to keep **both** open: a script in your editor and a REPL in the terminal for trying out small pieces.
+
+## Common mistakes
+
+### 1. "can't open file … No such file or directory"
+
+```text
+python3: can't open file '/Users/you/hello.py': [Errno 2] No such file or directory
+```
+
+The terminal's current folder isn't the folder that holds your file. Look at the path in the message: it shows where Python looked. **Fix:** `cd` into the right folder, or give the full path to the file.
+
+### 2. Saving as `hello.py.txt`
+
+Some text editors, like Notepad, add `.txt` automatically. The folder then holds a file that isn't really `hello.py`:
+
+```text
+% ls
+hello.py.txt
+% python3 hello.py
+python3: can't open file '/Users/you/python-course/hello.py': [Errno 2] No such file or directory
+```
+
+**Fix:** use a code editor, or choose *All files* when saving, and turn on file extensions in your file manager so you can see the real name.
+
+### 3. Running before you save
+
+Most editors run the file that's saved on disk, not what's on your screen. You changed the second line to print `"Bye!"`, pressed Run, and still see the old output:
+
+```text
+Hello from a file!
+This line runs second.
+And this one runs last.
+```
+
+**Fix:** save first (**Ctrl + S**, or **⌘ + S** on macOS). An unsaved file usually shows a dot or `●` on its tab. You can also turn on *Auto Save* in VS Code's **File** menu.
+
+## Practice
+
+### 1. REPL vs. file
+
+Type these three lines into the REPL, then save the same lines as `compare.py` and run it. What's different?
+
+```python
+3 + 4
+len("hello")
+print("done")
+```
+
+::: details Solution
+**REPL:**
+
+```text
+>>> 3 + 4
+7
+>>> len("hello")
+5
+>>> print("done")
+done
+```
+
+**Script:**
+
+```text
+done
+```
+
+The REPL shows the value of every expression. A script only shows what you `print()`.
+:::
+
+### 2. Your first saved program
+
+Create `about_me.py` that prints three lines: your name, your favorite food, and one thing you want to build with Python. Run it from the terminal **and** from your editor.
+
+::: details Solution
+```python
+print("Name: Bekzod")
+print("Favorite food: plov")
+print("Goal: a program that tracks my expenses")
+```
+
+Run it with `python about_me.py` (or `python3 about_me.py`) from the folder where you saved it.
+:::
+
+### 3. Fix the script
+
+A classmate's script prints nothing. Fix it so it shows the total price.
+
+```python
+price = 12
+quantity = 3
+price * quantity
+```
+
+::: details Solution
+```python
+price = 12
+quantity = 3
+print(price * quantity)
+```
+
+The last line calculated `36` but never showed it. Scripts only display what you pass to `print()`.
+:::
+
+### 4. Find the file
+
+You saved `hello.py` in `Documents/python-course`, but running `python hello.py` gives *No such file or directory*. List two different ways to fix it.
+
+::: details Solution
+1. Move into the folder first: `cd Documents/python-course`, then run `python hello.py`.
+2. Stay where you are and give the path: `python Documents/python-course/hello.py`.
+
+A third option is to open the folder in VS Code and use its built-in terminal, which starts in the right place.
+:::
+
+### 5. The REPL remembered, the script didn't
+
+Ali typed `city = "Samarkand"` in the REPL. Then he saved a script `greet.py` with just one line, `print(city)`, and ran it in the terminal:
+
+```text
+Traceback (most recent call last):
+ File "/Users/ali/python-course/greet.py", line 1, in
+ print(city)
+ ^^^^
+NameError: name 'city' is not defined
+```
+
+Why does the script fail when the REPL knew `city`? Fix the script so it prints `Samarkand`.
+
+::: details Solution
+```python
+city = "Samarkand"
+print(city)
+```
+
+```text
+Samarkand
+```
+
+The REPL and the script are separate runs of Python. A variable created in the REPL lives only until you leave that REPL. A script starts with nothing, so it must create every variable it uses. The same is true for each **▶ Run** on these pages.
+:::
+
+## Recap
+
+- The **REPL** (`>>>`) runs one line at a time and shows values automatically. Great for experiments, but nothing is saved.
+- A **script** is a `.py` file run top to bottom with `python file.py`. It only shows what you `print()`.
+- The terminal works inside a **current folder**. Python looks for your file there.
+- Editors run your file for you, so remember to **save first**.
+- Each run starts fresh: a script can't see variables from the REPL. Don't name your files after standard modules like `random.py`.
+
+## Further reading
+
+- [Python Tutorial - Using the Python Interpreter](https://docs.python.org/3/tutorial/interpreter.html)
+- [Command line and environment](https://docs.python.org/3/using/cmdline.html)
+- [Getting started with Python in VS Code](https://code.visualstudio.com/docs/python/python-tutorial)
diff --git a/docs/lessons/01-getting-started/04-hello-world.md b/docs/lessons/01-getting-started/04-hello-world.md
new file mode 100644
index 0000000..66e18bd
--- /dev/null
+++ b/docs/lessons/01-getting-started/04-hello-world.md
@@ -0,0 +1,374 @@
+---
+title: Hello, World!
+description: "Write your first real Python programs with print(): text, quotes, multiple values, special characters, and controlling separators and line endings."
+---
+
+# Hello, World!
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- How `print()` works: calling a function with **arguments**
+- How to write text (strings) with single, double, and triple quotes
+- How to print several values at once
+- How to use `\n`, `\t`, and other special characters
+- How to control spacing and line endings with `sep` and `end`
+:::
+
+## Why it matters
+
+Printing is how your program talks to you. Before you learn anything else, you need a reliable way to **see** what your code is doing. Programmers use `print()` their whole career, both to show results and to find bugs.
+
+By tradition, the first program in a new language prints *Hello, world!*
+
+```python
+print("Hello, world!")
+```
+
+```text
+Hello, world!
+```
+
+## Anatomy of a function call
+
+```text
+print("Hello, world!")
+| | | |
+| | | +-- closing parenthesis
+| | +---------- the argument: a string (text) value
+| +------------------ opening parenthesis: "call this function"
++----------------------- the function's name
+```
+
+- A **function** is a named piece of code that does a job. `print` is **built in**: it's always available.
+- **Calling** a function means running it. You call a function by writing its name followed by parentheses.
+- The value inside the parentheses is an **argument**: the input you give the function.
+
+Every function call has this shape: `name(arguments)`. You'll use hundreds of functions, and they all look like this.
+
+## Strings: writing text
+
+A piece of text in Python is called a **string**. You create one by putting text inside quotes. Single and double quotes work the same way:
+
+```python
+print("Double quotes work.")
+print('Single quotes work too.')
+```
+
+Pick one style and use it consistently. This course uses double quotes. The other kind is handy when your text contains a quote character:
+
+```python
+print("It's a sunny day.")
+print('She said "hello" and left.')
+```
+
+Or you can put a **backslash** before a quote, so Python treats it as a normal character instead of the end of the string:
+
+```python
+print("She said \"hello\" and left.")
+print('It\'s a sunny day.')
+```
+
+### Text across several lines
+
+Triple quotes (`"""` or `'''`) let a string span multiple lines exactly as you type them:
+
+```python
+print("""Shopping list:
+- bread
+- milk
+- apples""")
+```
+
+```text
+Shopping list:
+- bread
+- milk
+- apples
+```
+
+## Special characters: escape sequences
+
+A backslash followed by a letter makes a special character. These are called **escape sequences**:
+
+| Sequence | Meaning |
+|---|---|
+| `\n` | New line |
+| `\t` | Tab (a wide space, good for lining up columns) |
+| `\\` | A real backslash |
+| `\"` and `\'` | A quote character |
+
+```python
+print("Line one\nLine two")
+print("Name:\tAziza")
+print("Age:\t20")
+print("Folder: C:\\Users\\aziza")
+```
+
+```text
+Line one
+Line two
+Name: Aziza
+Age: 20
+Folder: C:\Users\aziza
+```
+
+::: warning Windows paths and single backslashes
+If you write a path with single backslashes, Python still reads each backslash as the start of an escape sequence. In `"C:\new\data"`, the `\n` quietly becomes a new line. `\d` isn't a known escape sequence, so Python 3.12 and newer also print a warning:
+
+```py
+print("Folder: C:\new\data")
+```
+
+```text
+SyntaxWarning: "\d" is an invalid escape sequence. Such sequences will not work in the future. Did you mean "\\d"? A raw string is also an option.
+Folder: C:
+ew\data
+```
+
+Either double every backslash, or put `r` before the quotes to make a **raw string**. In a raw string, backslashes are just backslashes:
+
+```python
+print(r"Folder: C:\new\data")
+```
+
+```text
+Folder: C:\new\data
+```
+:::
+
+## Printing several values
+
+Give `print()` several arguments, separated by commas. It prints them in order, with **one space between each**:
+
+```python
+print("Python", "is", "fun")
+print("Year:", 2026)
+print("2 + 3 =", 2 + 3)
+```
+
+```text
+Python is fun
+Year: 2026
+2 + 3 = 5
+```
+
+Notice `2026` and `2 + 3` have **no quotes**. They're numbers, not text. Python calculates `2 + 3` first and then prints the result. You'll learn more about numbers soon.
+
+### Empty lines
+
+`print()` with nothing inside prints a blank line, which is handy for spacing out your output:
+
+```python
+print("Report")
+print()
+print("All systems OK")
+```
+
+## Controlling the output: `sep` and `end`
+
+`print()` has two optional settings, given as **keyword arguments** in the form `name=value`:
+
+- **`sep`**: what goes *between* values (the default is a space `" "`)
+- **`end`**: what goes *after* the last value (the default is a new line `"\n"`)
+
+```python
+print("2026", "09", "15", sep="-")
+print("a", "b", "c", sep="")
+print("Loading", end="")
+print("...", end="")
+print(" done!")
+```
+
+```text
+2026-09-15
+abc
+Loading... done!
+```
+
+Because `end=""` removes the automatic new line, the next `print()` continues on the same line.
+
+## Programs run top to bottom
+
+Python runs one line after another, in order. Each `print()` call finishes before the next one starts:
+
+```python
+print("1. Wake up")
+print("2. Make tea")
+print("3. Learn Python")
+```
+
+Rearranging the lines changes the output. That sounds obvious, but "which line runs first?" is the question behind a lot of bugs.
+
+## Try it
+
+Make a small "business card" for yourself. Try `\t` to line up the values.
+
+
+
+`"=" * 30` repeats the string 30 times. Try changing the number.
+
+## Common mistakes
+
+### 1. Mismatched quotes
+
+```py
+print("Hello')
+```
+
+```text
+SyntaxError: unterminated string literal (detected at line 1)
+```
+
+A string must start and end with the **same** kind of quote.
+
+### 2. A quote inside a string
+
+```py
+print('It's raining')
+```
+
+```text
+SyntaxError: unterminated string literal (detected at line 1)
+```
+
+Python thinks the string ends at the apostrophe in `It's`. **Fix:** `print("It's raining")` or `print('It\'s raining')`.
+
+### 3. Forgetting the comma between values
+
+```py
+print("Total:" 42)
+```
+
+```text
+SyntaxError: invalid syntax. Perhaps you forgot a comma?
+```
+
+Python even suggests the fix. Arguments must be separated by commas: `print("Total:", 42)`.
+
+### 4. Quoting a calculation
+
+```python
+print("7 * 6") # prints the text 7 * 6
+print(7 * 6) # prints 42
+```
+
+Quotes make text. If you want Python to calculate something, leave the quotes off.
+
+## Practice
+
+### 1. Three lines, one call
+
+Print this using a **single** `print()` call:
+
+```text
+Roses are red
+Violets are blue
+Python is fun
+```
+
+::: details Solution
+```python
+print("Roses are red\nViolets are blue\nPython is fun")
+```
+
+A triple-quoted string also works.
+:::
+
+### 2. Quotes in the text
+
+Print exactly this line:
+
+```text
+The teacher said: "Don't forget the colon!"
+```
+
+::: details Solution
+```python
+print('The teacher said: "Don\'t forget the colon!"')
+```
+
+or
+
+```python
+print("The teacher said: \"Don't forget the colon!\"")
+```
+:::
+
+### 3. Dates and times
+
+Print the date `15/09/2026` and the time `08:30`, giving the day, month, and year (and the hours and minutes) as **separate values**. Use `sep` instead of typing `/` and `:` yourself.
+
+::: details Solution
+```python
+print(15, "09", 2026, sep="/")
+print("08", "30", sep=":")
+```
+
+`"09"` and `"08"` are written as strings, because Python doesn't allow leading zeros like `09` in whole numbers (`print(09)` is a `SyntaxError`).
+:::
+
+### 4. A tidy table
+
+Print this table with `\t` so the columns line up:
+
+```text
+Item Qty Price
+Tea 2 3.00
+Samsa 4 4.00
+```
+
+::: details Solution
+```python
+print("Item\tQty\tPrice")
+print("Tea\t2\t3.00")
+print("Samsa\t4\t4.00")
+```
+
+Or with `sep`:
+
+```python
+print("Item", "Qty", "Price", sep="\t")
+print("Tea", 2, "3.00", sep="\t")
+print("Samsa", 4, "4.00", sep="\t")
+```
+:::
+
+### 5. Progress bar
+
+Using several `print()` calls with `end`, produce this **single** line:
+
+```text
+[#####] 100%
+```
+
+Print the `[`, then each `#` with its own `print()` call, then the closing part.
+
+::: details Solution
+```python
+print("[", end="")
+print("#", end="")
+print("#", end="")
+print("#", end="")
+print("#", end="")
+print("#", end="")
+print("] 100%")
+```
+
+Writing the same line five times is tedious. In the **Loops** module, you'll do this in two lines with a `for` loop.
+:::
+
+## Recap
+
+- `print()` is a built-in **function**. Call it with `name(arguments)`.
+- Text values are **strings**, written in `"double"`, `'single'`, or `"""triple"""` quotes.
+- Escape sequences: `\n` for a new line, `\t` for a tab, and `\"` or `\\` for a quote or backslash.
+- `print(a, b, c)` prints values separated by spaces. `print()` alone prints an empty line.
+- `sep=` changes the separator and `end=` changes what's printed at the end.
+- Code runs **top to bottom**.
+
+## Further reading
+
+- [Built-in functions - `print()`](https://docs.python.org/3/library/functions.html#print)
+- [Python Tutorial - Using Python as a Calculator (Text)](https://docs.python.org/3/tutorial/introduction.html#text)
+- [String and bytes literals (escape sequences)](https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals)
diff --git a/docs/lessons/01-getting-started/05-comments-and-style.md b/docs/lessons/01-getting-started/05-comments-and-style.md
new file mode 100644
index 0000000..9fac42e
--- /dev/null
+++ b/docs/lessons/01-getting-started/05-comments-and-style.md
@@ -0,0 +1,374 @@
+---
+title: Comments and Code Style
+description: "Write comments that help, and follow Python's style guide (PEP 8): naming, indentation, spacing, and line length."
+---
+
+# Comments and Code Style
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- How to write comments with `#`, and what Python does with them
+- What makes a comment **useful** and what makes it noise
+- How to "comment out" code while testing
+- The basics of **PEP 8**, Python's official style guide
+- Why indentation is part of Python's grammar, not just decoration
+:::
+
+## Why it matters
+
+Code is read far more often than it's written: by teammates, by people answering your questions online, and by *you, three weeks from now*. Python's design puts readability first (remember *"Readability counts."* from the Zen of Python). Comments and consistent style are how you keep your own code readable.
+
+## Writing comments
+
+A **comment** starts with `#`. Python ignores everything from the `#` to the end of the line:
+
+```python
+# Calculate the price after a 10% discount
+price = 50
+discounted = price * 0.9
+print(discounted) # 45.0
+```
+
+- A **full-line comment** sits on its own line, above the code it describes.
+- An **inline comment** sits at the end of a line of code. Put **two spaces** before the `#` and one space after it.
+
+A `#` inside a string is just a character, not a comment:
+
+```python
+print("Use # for comments") # this part is the comment
+```
+
+Python has no special block-comment syntax. For several lines, start each one with `#`:
+
+```python
+# This program prints a receipt.
+# It uses fixed prices for now; later lessons
+# will read them from a file.
+print("Receipt")
+```
+
+## Good comments explain *why*
+
+Beginners often write comments that repeat the code. Those don't help, because the code already says *what* happens.
+
+```python
+# Bad: noise that repeats the code
+count = 0 # set count to 0
+count = count + 1 # add 1 to count
+```
+
+Useful comments explain **why** the code is the way it is, or give **context** the code can't show:
+
+```python
+# Good: explains why
+seconds = 90
+timeout = seconds + 5 # servers can be a few seconds slow; allow a margin
+
+# Good: gives context the code can't
+tax_rate = 0.12 # Uzbekistan VAT, 12% (check yearly)
+```
+
+A few rules of thumb:
+
+1. **Clear code first.** If you need a comment to explain a confusing name, rename it instead: `d = 7` with a comment is worse than `days_until_deadline = 7`.
+2. **Explain decisions, warnings, and units.** Examples: *"in centimeters"*, *"must run before saving"*, *"this list is sorted"*.
+3. **Keep comments up to date.** A wrong comment is worse than no comment.
+4. **Write full sentences** for full-line comments, starting with a capital letter.
+
+## Commenting out code
+
+Putting `#` in front of a line **disables** it without deleting it. This is useful for testing:
+
+```python
+print("Step 1")
+# print("Step 2 — temporarily turned off")
+print("Step 3")
+```
+
+```text
+Step 1
+Step 3
+```
+
+In most editors, **Ctrl + /** (macOS: **⌘ + /**) comments or uncomments the selected lines.
+
+Don't leave large blocks of commented-out code in finished programs. They clutter the file, and it's unclear whether they still matter.
+
+## A quick look at docstrings
+
+You'll sometimes see text in triple quotes right at the top of a file or just inside a function:
+
+```python
+"""Receipt printer: prints a simple shop receipt."""
+
+print("Receipt")
+```
+
+That's a **docstring**, a string that documents a module, function, or class. Unlike `#` comments, Python keeps docstrings so tools (and `help()`) can show them. You'll write them properly in the **Functions** module.
+
+## PEP 8: Python's style guide
+
+**PEP 8** is the official style guide for Python code. (A *PEP* is a Python Enhancement Proposal, a design document for Python.) Almost all Python projects follow it, so following it makes your code look familiar to every Python programmer.
+
+You don't need to memorize all of it. These are the rules that matter most right now.
+
+### Indentation: 4 spaces
+
+Python uses **indentation** (spaces at the start of a line) to group code into blocks. Use **4 spaces per level**, never tabs:
+
+```python
+temperature = 31
+
+if temperature > 30:
+ print("It's hot.")
+ print("Drink water.")
+
+print("Have a nice day.")
+```
+
+The two indented lines belong to the `if`. The last line doesn't. You'll learn `if` properly in the **Making Decisions** module. For now, notice that indentation isn't just style in Python: **it changes what the code means**. Wrong indentation causes errors (see *Common mistakes* below).
+
+Code editors insert 4 spaces when you press **Tab** in a `.py` file.
+
+### Names: `snake_case`
+
+| Kind of name | Style | Examples |
+|---|---|---|
+| Variables and functions | `lower_case_with_underscores` | `total_price`, `user_name`, `print_receipt` |
+| Constants (values that never change) | `UPPER_CASE` | `MAX_USERS`, `TAX_RATE` |
+| Classes (later in the course) | `CapitalizedWords` | `ShoppingCart`, `Student` |
+
+Choose names that say what the value **means**:
+
+```python
+# Bad: hard to read
+x = 3
+y = 12.5
+z = x * y
+
+# Good: readable without comments
+quantity = 3
+unit_price = 12.5
+total = quantity * unit_price
+print(total)
+```
+
+### Spaces
+
+- Put one space around `=` and around most operators: `total = price * 2`.
+- Put a space after a comma, but not before it: `print("a", "b")`.
+- Don't put spaces just inside parentheses: `print("hi")`, not `print( "hi" )`.
+- For keyword arguments, don't put spaces around `=`: `print("a", "b", sep="-")`.
+
+```py
+# Bad: cramped and inconsistent
+total=price*2+tax
+print( "Total:" ,total )
+
+# Good: follows PEP 8
+total = price * 2 + tax
+print("Total:", total)
+```
+
+### Line length and blank lines
+
+- Keep lines to about **79 characters**. Many teams allow up to 88 or 99. Long lines are hard to read side by side.
+- Use **blank lines** to separate logical sections of a program, like paragraphs in writing.
+
+```python
+# Inputs
+width = 4
+height = 3
+
+# Calculation
+area = width * height
+
+# Output
+print("Area:", area)
+```
+
+::: info Tools do this for you
+Later, you can install a **formatter** that fixes spacing automatically and a **linter** that points out style problems. For now, following these few rules by hand builds good habits.
+:::
+
+## Try it
+
+This program works, but it's hard to read. Rename the variables, fix the spacing, and add **one** useful comment. Make sure it still prints the same result.
+
+
+
+## Common mistakes
+
+### 1. Unexpected indentation
+
+```py
+print("start")
+ print("indented for no reason")
+```
+
+```text
+IndentationError: unexpected indent
+```
+
+Only indent code that belongs to a block, such as the body of an `if`. **Fix:** remove the extra spaces.
+
+### 2. Missing indentation
+
+```py
+if 5 > 3:
+print("five is bigger")
+```
+
+```text
+IndentationError: expected an indented block after 'if' statement on line 1
+```
+
+**Fix:** indent the body of the `if` with 4 spaces.
+
+### 3. Mixing tabs and spaces
+
+```text
+TabError: inconsistent use of tabs and spaces in indentation
+```
+
+The lines *look* aligned, but some use a tab character and some use spaces. **Fix:** set your editor to insert spaces (VS Code does this by default for Python). In VS Code, run **Convert Indentation to Spaces** from the Command Palette.
+
+### 4. Comments that lie
+
+```python
+discount = 0.2 # 10% discount
+```
+
+The code says 20%, but the comment says 10%. Which one is right? **Fix:** update comments whenever you change the code, or remove comments the code already makes clear.
+
+## Practice
+
+### 1. Clean it up
+
+Rewrite this code following PEP 8 spacing. Don't change what it prints.
+
+```python
+name="Aziza"
+age=20
+print( "Name:",name ,"Age:" ,age )
+```
+
+::: details Solution
+```python
+name = "Aziza"
+age = 20
+print("Name:", name, "Age:", age)
+```
+:::
+
+### 2. Better names
+
+Give these variables meaningful `snake_case` names:
+
+```python
+n = "Tashkent"
+p = 3100000
+FlightPriceSom = 1250000
+```
+
+::: details Solution
+```python
+city = "Tashkent"
+population = 3100000
+flight_price_som = 1250000
+```
+
+`FlightPriceSom` uses the class style (`CapitalizedWords`). Variables use `snake_case`.
+:::
+
+### 3. Useful or noise?
+
+For each comment, decide whether it's **useful** or **noise**, and explain why.
+
+```python
+speed = 120 # speed
+distance = 300 # kilometers
+hours = distance / speed # divide distance by speed
+hours = hours + 0.5 # add a 30-minute rest stop
+```
+
+::: details Solution
+1. `# speed`: **noise**. The name already says it. A useful version would give the unit: `# km/h`.
+2. `# kilometers`: **useful**. It gives the unit, which the code can't show.
+3. `# divide distance by speed`: **noise**. It repeats the code.
+4. `# add a 30-minute rest stop`: **useful**. It explains *why* 0.5 is added.
+:::
+
+### 4. Find the bug with comments
+
+This program prints the wrong total. Comment out lines one at a time to find which line causes the problem, then fix it.
+
+```python
+apples = 4
+pears = 3
+apples = 40
+total_fruit = apples + pears
+print("Total fruit:", total_fruit)
+```
+
+The expected output is `Total fruit: 7`.
+
+::: details Solution
+Commenting out `apples = 40` makes the program print `Total fruit: 7`. That line overwrote the correct value, so delete it:
+
+```python
+apples = 4
+pears = 3
+total_fruit = apples + pears
+print("Total fruit:", total_fruit)
+```
+
+Temporarily disabling lines like this is a simple but effective debugging technique.
+:::
+
+### 5. Style review
+
+Rewrite this program so it follows everything in this lesson: meaningful names, PEP 8 spacing, blank lines between sections, and one or two comments that explain **why**. It should print the same result.
+
+```python
+W=5.5
+H=3
+r=W*H
+pc=r*85000 #
+print ("Room cost:",pc)
+```
+
+::: details Solution
+```python
+# Room size in meters
+width = 5.5
+height = 3
+
+area = width * height
+
+# Flooring price in som per square meter (supplier quote)
+PRICE_PER_SQUARE_METER = 85000
+cost = area * PRICE_PER_SQUARE_METER
+
+print("Room cost:", cost)
+```
+
+- Names say what each value means, and the fixed price is a constant in `UPPER_CASE`.
+- Comments give units and where the price comes from, which the code can't show.
+- The empty `#` comment was removed, and the spacing around `=`, `*`, and after commas was fixed.
+:::
+
+## Recap
+
+- `#` starts a comment, and Python ignores the rest of the line.
+- Good comments explain **why**, give units, or give context. Don't restate the code.
+- Commenting out lines is a quick way to test and debug. Clean up afterwards.
+- **PEP 8** is Python's style guide: 4-space indentation, `snake_case` names, spaces around `=` and operators, lines of about 79 characters.
+- Indentation is **part of Python's grammar**. Wrong indentation causes `IndentationError` or `TabError`.
+
+## Further reading
+
+- [PEP 8 - Style Guide for Python Code](https://peps.python.org/pep-0008/)
+- [Python Tutorial - Coding style](https://docs.python.org/3/tutorial/controlflow.html#intermezzo-coding-style)
+- [PEP 257 - Docstring conventions](https://peps.python.org/pep-0257/)
diff --git a/docs/lessons/02-values-and-variables/01-variables.md b/docs/lessons/02-values-and-variables/01-variables.md
new file mode 100644
index 0000000..07d1838
--- /dev/null
+++ b/docs/lessons/02-values-and-variables/01-variables.md
@@ -0,0 +1,428 @@
+---
+title: Variables
+description: "Store values with variables: assignment, reassignment, naming rules, multiple assignment, and how Python names really work."
+---
+
+# Variables
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- How to create a variable with `=` and use it later
+- What happens when you **reassign** a variable
+- The rules and conventions for naming variables
+- How to assign several variables at once and swap two values
+- How to check a value's type with `type()`
+:::
+
+## Why it matters
+
+Programs work with information: a user's name, a price, a score, today's temperature. A **variable** gives a value a name, so you can use it, change it, and combine it with other values. Almost every line of code you write from now on will use variables.
+
+## Creating a variable
+
+Write a name, an equals sign, and a value:
+
+```python
+city = "Samarkand"
+population = 580000
+
+print(city)
+print(population)
+```
+
+```text
+Samarkand
+580000
+```
+
+`=` is the **assignment operator**. It doesn't mean "equals" as in math. Read it as **"make this name refer to this value"**:
+
+> `city = "Samarkand"` → *"let `city` refer to the text `Samarkand`"*
+
+Python first works out the value on the **right** side, then attaches the name on the **left** to it:
+
+```python
+price = 12000
+quantity = 3
+total = price * quantity # right side is calculated first: 36000
+
+print("Total:", total)
+```
+
+## Reassigning: variables can change
+
+A variable can be pointed at a new value at any time. The old value is forgotten:
+
+```python
+score = 10
+print(score)
+
+score = 25
+print(score)
+```
+
+```text
+10
+25
+```
+
+A very common pattern is updating a variable **using its own current value**:
+
+```python
+steps = 1000
+steps = steps + 500 # take the current value, add 500, store it back
+print(steps)
+```
+
+```text
+1500
+```
+
+This is so common that Python has a shortcut, `+=`. There are matching shortcuts for other operators too:
+
+```python
+steps = 1000
+steps += 500 # same as: steps = steps + 500
+steps -= 200 # same as: steps = steps - 200
+steps *= 2 # same as: steps = steps * 2
+print(steps)
+```
+
+```text
+2600
+```
+
+## Names are labels, not boxes
+
+{.lesson-diagram width=1536 height=1024 loading=lazy}
+
+You'll often hear variables described as "boxes that hold values". For Python, a better picture is a **name tag attached to a value**. Two names can be attached to the same value:
+
+```python
+a = "hello"
+b = a # b now refers to the same value as a
+a = "bye" # move the tag a to a new value; b is unchanged
+
+print(a)
+print(b)
+```
+
+```text
+bye
+hello
+```
+
+`b = a` doesn't create a link between the *names*. It makes `b` refer to whatever `a` refers to **at that moment**. Moving `a` later doesn't move `b`.
+
+This picture becomes important when you learn about lists, which can be changed in place.
+
+## Naming rules
+
+Python **requires** these rules:
+
+1. Names may contain **letters, digits, and underscores** (`_`).
+2. A name **can't start with a digit**.
+3. No spaces or symbols like `-`, `!`, `@`.
+4. Names are **case-sensitive**: `age`, `Age`, and `AGE` are three different variables.
+5. You can't use Python's **keywords**, words with a special meaning such as `if`, `for`, `class`, `True`, and `None`.
+
+| Name | Valid? | Why |
+|---|---|---|
+| `user_name` | | |
+| `total2` | | Digits are fine after the first character |
+| `_hidden` | | Underscore at the start is allowed |
+| `2nd_place` | | Starts with a digit |
+| `user-name` | | `-` means minus |
+| `first name` | | Space |
+| `class` | | Keyword |
+
+To see all keywords, run `import keyword` and `print(keyword.kwlist)`.
+
+## Naming conventions
+
+These are not enforced by Python, but every Python programmer follows them (see *Comments and Code Style*):
+
+- Use **`snake_case`**: lowercase words joined by underscores, like `monthly_salary`.
+- Choose **descriptive** names: `temperature_c` is better than `t`. Short names like `i` or `x` are fine for tiny, obvious uses.
+- Use **`UPPER_CASE`** for constants, values you don't intend to change: `MAX_ATTEMPTS = 3`.
+- Don't use the names of built-in functions, like `print`, `input`, `list`, `str`, `sum`, or `type`, as variable names (see *Common mistakes*).
+
+```python
+MAX_ATTEMPTS = 3
+attempts_left = MAX_ATTEMPTS
+attempts_left -= 1
+print("Attempts left:", attempts_left)
+```
+
+## Several variables at once
+
+You can assign several names in one line, matching values left to right:
+
+```python
+name, age, city = "Dilnoza", 22, "Bukhara"
+print(name, age, city)
+```
+
+This gives a neat way to **swap** two values, with no temporary variable needed:
+
+```python
+left = "tea"
+right = "coffee"
+
+left, right = right, left
+
+print(left, right)
+```
+
+```text
+coffee tea
+```
+
+Python evaluates the whole right side (`right, left` → `"coffee", "tea"`) **before** assigning anything, which is why the swap works.
+
+You can also give several names the same value:
+
+```python
+x = y = 0
+print(x, y)
+```
+
+## Every value has a type
+
+Values come in different **types**: whole numbers, decimal numbers, text, and more. The built-in `type()` function tells you which:
+
+```python
+print(type(42))
+print(type(3.14))
+print(type("hello"))
+print(type(True))
+```
+
+```text
+
+
+
+
+```
+
+| Type | Name | Example |
+|---|---|---|
+| `int` | integer (whole number) | `42`, `-7`, `0` |
+| `float` | floating-point (decimal) number | `3.14`, `-0.5`, `2.0` |
+| `str` | string (text) | `"hello"`, `'42'` |
+| `bool` | boolean (true/false) | `True`, `False` |
+| `NoneType` | "no value" | `None` (the only value of this type) |
+
+`None` means "nothing here yet". Use it when a variable needs to exist before you know its value:
+
+```python
+best_score = None
+print(best_score)
+print(type(best_score))
+```
+
+```text
+None
+
+```
+
+`None` is not `0` and not an empty string. It's a separate value that says "unknown" or "not set". You'll meet it again with functions and `if` statements.
+
+In Python the **variable** has no fixed type. The **value** does. The same name can refer to a number now and a string later:
+
+```python
+thing = 5
+print(type(thing))
+thing = "five"
+print(type(thing))
+```
+
+That flexibility is convenient, but reusing one name for different kinds of data makes code confusing. Keep one meaning per variable.
+
+The next lessons cover numbers, strings, and booleans in detail.
+
+## Try it
+
+Change the values, add a `discount` variable, and print the final price.
+
+
+
+## Common mistakes
+
+### 1. Using a variable before creating it (or misspelling it)
+
+```py
+total_price = 500
+print(total_prise)
+```
+
+```text
+NameError: name 'total_prise' is not defined. Did you mean: 'total_price'?
+```
+
+Python reads top to bottom, so a variable must be assigned **before** it's used, and spelled exactly the same way.
+
+### 2. Invalid names
+
+```py
+2nd_place = "Bekzod"
+```
+
+```text
+SyntaxError: invalid decimal literal
+```
+
+The message is confusing, but the cause is the name starting with a digit. **Fix:** `second_place`.
+
+### 3. Mixing up the sides
+
+```py
+5 = x
+```
+
+```text
+SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?
+```
+
+The **name goes on the left**, the value on the right: `x = 5`.
+
+### 4. Hiding a built-in function
+
+```py
+print = "Hello"
+print("Hi")
+```
+
+```text
+TypeError: 'str' object is not callable
+```
+
+After `print = "Hello"`, the name `print` refers to a string instead of the function. **Fix:** choose another name, like `message`. In the REPL, restart Python to get `print` back.
+
+## Practice
+
+### 1. Trace the values
+
+Without running it, write down what this prints. Then run it to check.
+
+```python
+a = 4
+b = a * 2
+a = 10
+b += a
+print(a, b)
+```
+
+::: details Solution
+```text
+10 18
+```
+
+`b` becomes `8` (4 × 2). Then `a` changes to `10`, which doesn't affect `b`. Then `b += a` makes `b` equal to `8 + 10 = 18`.
+:::
+
+### 2. Personal info
+
+Create variables for your first name, birth year, and city. Print one sentence using all three, for example `Aziza was born in 2004 and lives in Tashkent`.
+
+::: details Solution
+```python
+first_name = "Aziza"
+birth_year = 2004
+city = "Tashkent"
+
+print(first_name, "was born in", birth_year, "and lives in", city)
+```
+:::
+
+### 3. Swap
+
+Swap the values of `morning` and `evening` so the program prints `evening: coffee` and `morning: tea` on separate lines. Don't retype the strings.
+
+```python
+morning = "coffee"
+evening = "tea"
+# your code here
+```
+
+::: details Solution
+```python
+morning = "coffee"
+evening = "tea"
+
+morning, evening = evening, morning
+
+print("evening:", evening)
+print("morning:", morning)
+```
+:::
+
+### 4. Fix the names
+
+This code won't run. Fix every name so it runs and follows the conventions, without changing what it prints.
+
+```py
+1st-item = "pen"
+Item Price = 3000
+class = 2
+print(1st-item, Item Price * class)
+```
+
+::: details Solution
+```python
+first_item = "pen"
+item_price = 3000
+quantity = 2
+print(first_item, item_price * quantity)
+```
+
+- `1st-item` starts with a digit and uses `-`.
+- `Item Price` contains a space and uses capitals.
+- `class` is a keyword.
+:::
+
+### 5. Savings tracker
+
+Start with `savings = 0`. Using only `+=` and `-=` on separate lines, record these events, and print `savings` after each one:
+
+1. You receive 200,000 som.
+2. You spend 45,000 som.
+3. You receive 150,000 som.
+4. You spend 80,000 som.
+
+The final balance should be `225000`.
+
+::: details Solution
+```python
+savings = 0
+
+savings += 200000
+print("After income:", savings)
+
+savings -= 45000
+print("After spending:", savings)
+
+savings += 150000
+print("After income:", savings)
+
+savings -= 80000
+print("After spending:", savings)
+```
+
+Printing after every step is a simple habit that makes bugs easy to spot.
+:::
+
+## Recap
+
+- `name = value` creates or updates a variable. The right side is evaluated first.
+- Reassigning replaces the old value. `+=`, `-=`, and `*=` update a variable using its current value.
+- Names are **labels** for values. `b = a` copies the reference at that moment, not a permanent link.
+- Names use letters, digits, and `_`, can't start with a digit, are case-sensitive, and can't be keywords. Use `snake_case`.
+- `a, b = b, a` swaps two values. `type(value)` shows the type of a value.
+
+## Further reading
+
+- [Python Tutorial - Numbers and variables](https://docs.python.org/3/tutorial/introduction.html#numbers)
+- [Assignment statements](https://docs.python.org/3/reference/simple_stmts.html#assignment-statements)
+- [Keywords](https://docs.python.org/3/reference/lexical_analysis.html#keywords)
diff --git a/docs/lessons/02-values-and-variables/02-numbers-and-math.md b/docs/lessons/02-values-and-variables/02-numbers-and-math.md
new file mode 100644
index 0000000..a2d3eda
--- /dev/null
+++ b/docs/lessons/02-values-and-variables/02-numbers-and-math.md
@@ -0,0 +1,455 @@
+---
+title: Numbers and Math
+description: "Work with integers and floats: arithmetic operators, integer division and remainder, operator precedence, rounding, and why 0.1 + 0.2 isn't exactly 0.3."
+---
+
+# Numbers and Math
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- The two main number types: `int` and `float`
+- All the arithmetic operators, including `//`, `%`, and `**`
+- The order Python calculates in (operator precedence)
+- Rounding and a few useful built-in functions
+- Why decimal numbers are sometimes slightly off, and what to do about it
+:::
+
+## Why it matters
+
+Prices, distances, scores, times, percentages: most programs calculate something. Python is a very good calculator, but it has a few rules (and surprises) you need to know to get correct results.
+
+## Two kinds of numbers
+
+```python
+students = 32 # int: a whole number
+height = 1.75 # float: a number with a decimal point
+
+print(type(students))
+print(type(height))
+```
+
+```text
+
+
+```
+
+- **`int`** (integer): whole numbers like `0`, `42`, `-7`. There's no size limit in Python, so `2 ** 100` works fine.
+- **`float`** (floating-point): numbers with a decimal point, like `3.14`, `-0.5`, or `2.0`. Note that `2.0` is a float even though it's a whole number.
+
+For readability, you can put underscores inside long numbers. Python ignores them:
+
+```python
+population = 37_000_000
+print(population)
+```
+
+```text
+37000000
+```
+
+Very large or very small floats can be written in **scientific notation**: `e` means "times 10 to the power of". Python also prints tiny floats this way:
+
+```python
+speed_of_light = 3e8 # 3 × 10⁸ metres per second
+grain = 2.5e-3 # 0.0025 grams
+print(speed_of_light, grain)
+print(0.00001)
+```
+
+```text
+300000000.0 0.0025
+1e-05
+```
+
+A number written with `e` is always a float, even `3e8`.
+
+## Arithmetic operators
+
+| Operator | Meaning | Example | Result |
+|---|---|---|---|
+| `+` | Addition | `7 + 2` | `9` |
+| `-` | Subtraction | `7 - 2` | `5` |
+| `*` | Multiplication | `7 * 2` | `14` |
+| `/` | Division | `7 / 2` | `3.5` |
+| `//` | Floor division | `7 // 2` | `3` |
+| `%` | Remainder (modulo) | `7 % 2` | `1` |
+| `**` | Power | `7 ** 2` | `49` |
+
+```python
+print(7 + 2, 7 - 2, 7 * 2)
+print(7 / 2, 7 // 2, 7 % 2)
+print(2 ** 10)
+```
+
+```text
+9 5 14
+3.5 3 1
+1024
+```
+
+### `/` always gives a float
+
+Regular division always returns a float, even when the result is whole:
+
+```python
+print(10 / 2)
+```
+
+```text
+5.0
+```
+
+### `//` and `%`: whole parts and leftovers
+
+`//` gives how many **whole times** one number fits into another. `%` gives **what's left over**. They're a very useful pair:
+
+```python
+total_minutes = 135
+
+hours = total_minutes // 60 # 2 whole hours
+minutes = total_minutes % 60 # 15 minutes left over
+
+print(hours, "h", minutes, "min")
+```
+
+```text
+2 h 15 min
+```
+
+With a float, `//` still rounds down, but the result is a float: `7.5 // 2` is `3.0`, and `7.5 % 2` is `1.5`.
+
+When you need both answers, `divmod()` gives them in one step. It returns two values, which you can store in two variables at once:
+
+```python
+hours, minutes = divmod(135, 60)
+print(hours, "h", minutes, "min")
+```
+
+```text
+2 h 15 min
+```
+
+Common uses of `%`:
+
+- **Even or odd:** `n % 2` is `0` for even numbers and `1` for odd numbers.
+- **Last digit:** `n % 10` gives the last digit of a positive whole number.
+- **Wrapping around:** `(hour + 5) % 24` keeps a clock hour between 0 and 23.
+
+```python
+print(14 % 2) # 0 → even
+print(15 % 2) # 1 → odd
+print(2026 % 10) # 6 → last digit
+print((22 + 5) % 24) # 3 → 22:00 plus 5 hours is 03:00
+```
+
+::: details Negative numbers with `//` and `%`
+`//` rounds **down** (toward negative infinity), not toward zero: `-7 // 2` is `-4`, not `-3`. Then `-7 % 2` is `1`, because `-4 * 2 + 1 == -7`. You'll rarely need this, but it explains surprising results.
+:::
+
+## Mixing ints and floats
+
+If an operation mixes an `int` and a `float`, the result is a `float`:
+
+```python
+print(3 + 0.5)
+print(2 * 1.5)
+```
+
+```text
+3.5
+3.0
+```
+
+## Order of operations
+
+Python follows the usual math rules. From highest priority to lowest:
+
+1. `( )` parentheses
+2. `**` power
+3. `-x` negative sign
+4. `*`, `/`, `//`, `%` (left to right)
+5. `+`, `-` (left to right)
+
+```python
+print(2 + 3 * 4) # multiplication first
+print((2 + 3) * 4) # parentheses first
+print(-2 ** 2) # power before the negative sign
+print((-2) ** 2)
+```
+
+```text
+14
+20
+-4
+4
+```
+
+**When in doubt, add parentheses.** They make your intent clear to both Python and people:
+
+```python
+price = 80000
+discount_percent = 15
+final_price = price - (price * discount_percent / 100)
+print(final_price)
+```
+
+```text
+68000.0
+```
+
+## Updating numbers
+
+The shortcut operators from the *Variables* lesson work with every arithmetic operator:
+
+```python
+balance = 1000
+balance += 250 # 1250
+balance -= 100 # 1150
+balance *= 2 # 2300
+balance //= 3 # 766
+print(balance)
+```
+
+## Useful built-in functions
+
+```python
+print(abs(-12)) # absolute value
+print(round(3.14159, 2)) # round to 2 decimal places
+print(round(7.6)) # round to nearest whole number → int
+print(max(4, 9, 2)) # largest
+print(min(4, 9, 2)) # smallest
+print(pow(2, 5)) # same as 2 ** 5
+```
+
+```text
+12
+3.14
+8
+9
+2
+32
+```
+
+::: info How `round()` handles halves
+`round(2.5)` gives `2` and `round(3.5)` gives `4`. Python rounds exact halves to the nearest **even** number ("banker's rounding"), which avoids bias when rounding many values. This surprises many people, so remember it when a result looks one-off.
+
+Floats add one more surprise: `round(2.675, 2)` gives `2.67`, not `2.68`. That isn't banker's rounding. `2.675` is stored as a binary number slightly **below** 2.675 (more on this in *Floats aren't perfectly exact* below). For displaying money and measurements, the f-string formatting you'll learn soon is the usual tool.
+:::
+
+### The `math` module
+
+For more math, Python has a `math` module. You'll learn about modules later. For now, just know that `import math` makes these available:
+
+```python
+import math
+
+print(math.sqrt(49)) # square root
+print(math.pi) # π
+print(math.floor(4.7)) # round down
+print(math.ceil(4.2)) # round up
+```
+
+```text
+7.0
+3.141592653589793
+4
+5
+```
+
+## Floats aren't perfectly exact
+
+Try this:
+
+```python
+print(0.1 + 0.2)
+```
+
+```text
+0.30000000000000004
+```
+
+This isn't a Python bug. Computers store floats in **binary** (base 2), and some simple decimal numbers like `0.1` can't be stored exactly in binary, just as `1/3` can't be written exactly in decimal (`0.3333…`). Almost every programming language behaves this way.
+
+What to do about it:
+
+- For **displaying** results, round them: `round(0.1 + 0.2, 2)` gives `0.3`. You'll also learn to format numbers with f-strings.
+- For **comparing** floats, don't check for exact equality. Use `math.isclose()` (covered in *Booleans and Comparisons*).
+- For **money**, work in whole units where you can, for example tiyin or cents stored as `int`. Python also has a `decimal` module for exact decimal math.
+
+## Try it
+
+Convert a number of seconds into hours, minutes, and seconds. Try `3725`, then `86399`.
+
+
+
+## Common mistakes
+
+### 1. Dividing by zero
+
+```py
+print(10 / 0)
+```
+
+```text
+ZeroDivisionError: division by zero
+```
+
+`//` and `%` raise the same error. You'll learn to check for this with `if` in the next module.
+
+### 2. Using `^` for power
+
+```python
+print(2 ^ 3) # 1, not 8!
+print(2 ** 3) # 8
+```
+
+In Python, `^` is a *bitwise* operator, not "to the power of". Use `**`.
+
+### 3. Leaving out `*`
+
+```py
+width = 4
+area = 2width
+```
+
+```text
+SyntaxError: invalid decimal literal
+```
+
+Math notation lets you write `2x`, but Python needs the operator: `2 * width`.
+
+### 4. Forgetting precedence
+
+```python
+average = 80 + 90 / 2
+print(average) # 125.0, not 85.0
+```
+
+Division happens before addition. **Fix:** `(80 + 90) / 2`.
+
+## Practice
+
+### 1. Rectangle
+
+A room is 4.5 m wide and 6 m long. Print its **area** (width × length) and **perimeter** (2 × (width + length)).
+
+::: details Solution
+```python
+width = 4.5
+length = 6
+
+area = width * length
+perimeter = 2 * (width + length)
+
+print("Area:", area)
+print("Perimeter:", perimeter)
+```
+
+```text
+Area: 27.0
+Perimeter: 21.0
+```
+:::
+
+### 2. Temperature
+
+Convert `36.6` °C to Fahrenheit using `F = C × 9 / 5 + 32`, and print the result rounded to one decimal place.
+
+::: details Solution
+```python
+celsius = 36.6
+fahrenheit = celsius * 9 / 5 + 32
+print(round(fahrenheit, 1))
+```
+
+```text
+97.9
+```
+:::
+
+### 3. Sharing snacks
+
+There are 50 samsas and 7 friends. Each friend gets the same whole number of samsas. Print how many each friend gets and how many are left over.
+
+::: details Solution
+```python
+samsas = 50
+friends = 7
+
+each = samsas // friends
+left_over = samsas % friends
+
+print("Each friend gets:", each)
+print("Left over:", left_over)
+```
+
+```text
+Each friend gets: 7
+Left over: 1
+```
+:::
+
+### 4. Digit sum
+
+For a three-digit number such as `number = 472`, use `//` and `%` (no strings) to get each digit, and print the sum of the digits (`4 + 7 + 2 = 13`).
+
+::: details Solution
+```python
+number = 472
+
+hundreds = number // 100 # 4
+tens = (number // 10) % 10 # 7
+ones = number % 10 # 2
+
+print(hundreds + tens + ones)
+```
+
+`number // 10` removes the last digit (`47`), and `% 10` then takes the new last digit (`7`).
+:::
+
+### 5. Loan payment
+
+You borrow `P = 12_000_000` som at a monthly interest rate `r = 0.02` for `n = 12` months. The fixed monthly payment is:
+
+```text
+payment = P × r × (1 + r)ⁿ / ((1 + r)ⁿ − 1)
+```
+
+Calculate the payment and print it rounded to the nearest som. Then print the total you pay back over the year.
+
+::: details Solution
+```python
+principal = 12_000_000
+rate = 0.02
+months = 12
+
+growth = (1 + rate) ** months
+payment = principal * rate * growth / (growth - 1)
+
+print("Monthly payment:", round(payment))
+print("Total paid:", round(payment * months))
+```
+
+```text
+Monthly payment: 1134715
+Total paid: 13616582
+```
+
+Storing `(1 + rate) ** months` in its own variable avoids calculating it twice and makes the formula easier to read.
+:::
+
+## Recap
+
+- `int` is for whole numbers and `float` is for decimals. Mixing them gives a float.
+- Operators: `+ - * /` plus `//` (floor division), `%` (remainder), and `**` (power). `/` always returns a float.
+- Precedence: parentheses → `**` → unary `-` → `* / // %` → `+ -`. Use parentheses to be clear.
+- Useful functions: `abs`, `round`, `min`, `max`, and `math.sqrt`, `math.floor`, `math.ceil`.
+- Floats are approximate (`0.1 + 0.2`), so round results for display and don't compare floats for exact equality.
+
+## Further reading
+
+- [Python Tutorial - Using Python as a Calculator](https://docs.python.org/3/tutorial/introduction.html#numbers)
+- [Numeric types - int, float, complex](https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex)
+- [Floating-point arithmetic: issues and limitations](https://docs.python.org/3/tutorial/floatingpoint.html)
+- [`math` module](https://docs.python.org/3/library/math.html)
diff --git a/docs/lessons/02-values-and-variables/03-strings-basics.md b/docs/lessons/02-values-and-variables/03-strings-basics.md
new file mode 100644
index 0000000..321f5a5
--- /dev/null
+++ b/docs/lessons/02-values-and-variables/03-strings-basics.md
@@ -0,0 +1,427 @@
+---
+title: Strings
+description: "Work with text in Python: joining and repeating strings, length, indexing individual characters, immutability, the in operator, and a first look at Unicode and bytes."
+---
+
+# Strings
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- How to join strings with `+`, repeat them with `*`, and count characters with `len()`
+- How to get single characters with **indexing**, including negative indexes
+- Why strings can't be changed in place (immutability)
+- How to check whether text contains something with `in`
+- How Python stores characters as Unicode, and what `bytes` are
+:::
+
+## Why it matters
+
+Names, messages, emails, file names, passwords, web pages: a huge amount of real-world data is text. In Python, text is stored as a **string** (`str`), a sequence of characters. You already know how to write strings from *Hello, World!* This lesson shows how to take them apart and put them together.
+
+## Joining strings: `+`
+
+`+` **concatenates** (joins) strings end to end:
+
+```python
+first_name = "Aziza"
+last_name = "Karimova"
+
+full_name = first_name + " " + last_name
+print(full_name)
+```
+
+```text
+Aziza Karimova
+```
+
+`+` adds **no space** by itself, so you have to include one, as with `" "` above.
+
+## Repeating strings: `*`
+
+Multiplying a string by a whole number repeats it:
+
+```python
+print("ha" * 3)
+print("-" * 20)
+```
+
+```text
+hahaha
+--------------------
+```
+
+That's a quick way to draw lines and borders in text output.
+
+## Length: `len()`
+
+The built-in `len()` function returns how many characters a string has. Spaces and punctuation count too:
+
+```python
+password = "tea2go!"
+print(len(password))
+print(len("Hello, world!"))
+print(len(""))
+```
+
+```text
+7
+13
+0
+```
+
+`""` is the **empty string**: a string with no characters.
+
+## Indexing: getting one character
+
+{.lesson-diagram width=1536 height=1024 loading=lazy}
+
+Every character in a string has a position number called an **index**. Indexes **start at 0**:
+
+```text
+ P y t h o n
+ 0 1 2 3 4 5 ← index from the start
+-6 -5 -4 -3 -2 -1 ← index from the end
+```
+
+Put the index in square brackets to get that character:
+
+```python
+word = "Python"
+
+print(word[0]) # first character
+print(word[1])
+print(word[5]) # last character
+```
+
+```text
+P
+y
+n
+```
+
+### Negative indexes count from the end
+
+`-1` is the last character, `-2` is the second-to-last, and so on. This is handy when you don't know the length:
+
+```python
+word = "Python"
+print(word[-1])
+print(word[-2])
+```
+
+```text
+n
+o
+```
+
+The last index is always `len(word) - 1`, because counting starts at 0:
+
+```python
+word = "Python"
+print(word[len(word) - 1]) # same as word[-1]
+```
+
+::: info Why start at 0?
+Think of the index as "how many characters to skip from the start". To get the first character you skip 0. Most programming languages count this way, and you'll get used to it quickly.
+:::
+
+In the next lesson you'll learn **slicing**, which gets several characters at once (like `word[0:3]` → `"Pyt"`).
+
+## Strings can't be changed in place
+
+Strings are **immutable**: once a string is created, its characters can't be changed.
+
+```py
+word = "hello"
+word[0] = "H"
+```
+
+```text
+TypeError: 'str' object does not support item assignment
+```
+
+Instead, you build a **new** string and assign it to the variable:
+
+```python
+word = "hello"
+word = "H" + word[1:] # "H" + "ello"
+print(word)
+```
+
+```text
+Hello
+```
+
+(`word[1:]` means "from index 1 to the end". Slicing is explained in the next lesson.)
+
+Immutability sounds limiting, but it makes strings safe to share: if two variables refer to the same string, neither can change it for the other.
+
+## Checking contents: `in`
+
+`in` checks whether one string appears inside another. The result is `True` or `False`:
+
+```python
+email = "aziza@example.com"
+
+print("@" in email)
+print("gmail" in email)
+print("gmail" not in email)
+```
+
+```text
+True
+False
+True
+```
+
+The check is **case-sensitive**: `"Py" in "python"` is `False`. You'll use `True`/`False` results with `if` statements in the *Making Decisions* module.
+
+## Strings and numbers don't mix automatically
+
+`+` means *add* for numbers and *join* for strings. Python refuses to guess what you want when you mix them:
+
+```py
+age = 20
+print("Age: " + age)
+```
+
+```text
+TypeError: can only concatenate str (not "int") to str
+```
+
+You have three good options:
+
+```python
+age = 20
+
+print("Age:", age) # 1. separate arguments to print()
+print("Age: " + str(age)) # 2. convert the number with str()
+print(f"Age: {age}") # 3. an f-string (see the F-Strings lesson)
+```
+
+All three print `Age: 20`. The f-string is usually the clearest, and you'll learn it soon.
+
+## Text, Unicode and bytes
+
+A computer only stores numbers, so every character has a number too. Python uses **Unicode**, a standard that gives a number called a **code point** to every character in almost every writing system: Latin, Cyrillic, Arabic, emoji and more. `ord()` gives a character's code point, and `chr()` goes back:
+
+```python
+print(ord("A"), ord("ş"))
+print(chr(65), chr(351))
+```
+
+```text
+65 351
+A ş
+```
+
+`len()` counts code points, not what looks like a letter to you. In Uzbek Latin, `oʻ` is written with the letter `o` plus a separate **modifier letter** `ʻ`, so it counts as two characters:
+
+```python
+print(len("oʻ"))
+print(len("Oʻzbekiston"))
+print(ord("ʻ"), ord("'"))
+```
+
+```text
+2
+11
+699 39
+```
+
+The last line shows that `ʻ` (code point 699) and the keyboard apostrophe `'` (39) are **different characters**, even though they look alike. That matters when you search or compare text (see *Common mistakes*).
+
+### `str` and `bytes`
+
+A `str` holds characters. When text is saved to a file or sent over the internet, it has to become **bytes**: plain numbers from 0 to 255. The rules for turning characters into bytes are called an **encoding**, and UTF-8 is the one to use. `.encode()` turns a string into `bytes`, and `.decode()` turns it back:
+
+```python
+country = "Oʻzbekiston"
+data = country.encode("utf-8")
+
+print(data)
+print(len(data))
+print(data.decode("utf-8"))
+```
+
+```text
+b'O\xca\xbbzbekiston'
+12
+Oʻzbekiston
+```
+
+A `bytes` value is shown with a `b` before the quotes. Plain English letters take one byte each, but `ʻ` takes two (`\xca\xbb`), so the bytes are longer than the string. You'll rarely call `.encode()` yourself. It matters when you read and write files, which *Files and pathlib* covers, including why you should always say `encoding="utf-8"`.
+
+## Try it
+
+Build a username from a first and last name: the first letter of the first name, plus the whole last name, plus the length of the full name.
+
+
+
+## Common mistakes
+
+### 1. Index out of range
+
+```py
+word = "cat"
+print(word[3])
+```
+
+```text
+IndexError: string index out of range
+```
+
+`"cat"` has indexes `0`, `1`, and `2`. **Fix:** remember the last index is `len(word) - 1`, or use `word[-1]`.
+
+### 2. Forgetting spaces when joining
+
+```python
+city = "Tashkent"
+print("I live in" + city) # I live inTashkent
+```
+
+**Fix:** `"I live in " + city`, or `print("I live in", city)`.
+
+### 3. Adding numbers that are really strings
+
+```python
+apples = "5"
+pears = "5"
+print(apples + pears)
+```
+
+```text
+55
+```
+
+No error, just a wrong answer: both values are strings, so `+` joins them. This often happens with values from `input()`. **Fix:** convert them to numbers first, as shown in *Input and Type Conversion*: `int(apples) + int(pears)` gives `10`.
+
+### 4. Searching with the wrong apostrophe
+
+```python
+country = "Oʻzbekiston"
+print("O'zbekiston" == country)
+print("'" in country)
+```
+
+```text
+False
+False
+```
+
+The text was typed with the Uzbek letter `ʻ`, but the search uses the keyboard apostrophe `'`. They look alike but are different characters. **Fix:** use the same character in both places. If your data may contain both, replace one with the other first. You'll learn `.replace()` in the next lesson.
+
+## Practice
+
+### 1. Greeting
+
+Given `name = "Bekzod"`, use `+` to print `Hello, Bekzod!`
+
+::: details Solution
+```python
+name = "Bekzod"
+print("Hello, " + name + "!")
+```
+:::
+
+### 2. First and last
+
+For `word = "Samarkand"`, print the first character, the last character, and the length.
+
+::: details Solution
+```python
+word = "Samarkand"
+print(word[0])
+print(word[-1])
+print(len(word))
+```
+
+```text
+S
+d
+9
+```
+:::
+
+### 3. Initials
+
+Given `first = "aziza"` and `last = "karimova"`, print the initials `a.k.` using indexing and `+`.
+
+::: details Solution
+```python
+first = "aziza"
+last = "karimova"
+print(first[0] + "." + last[0] + ".")
+```
+
+In the next lesson you'll learn `.upper()`, which turns this into `A.K.`.
+:::
+
+### 4. A framed title
+
+Print a title inside a frame whose width **automatically matches** the text, using `*` and `len()`:
+
+```text
++----------------+
+| Python Journal |
++----------------+
+```
+
+Your code should still work if you change the title.
+
+::: details Solution
+```python
+title = "Python Journal"
+border = "+" + "-" * (len(title) + 2) + "+"
+
+print(border)
+print("| " + title + " |")
+print(border)
+```
+
+`len(title) + 2` accounts for the space on each side of the title.
+:::
+
+### 5. The middle character
+
+Print the middle character of a word. For an even-length word, print the character just **after** the middle. Store `"python"` (6 letters → `h`), `"plov"` (4 letters → `o`) and `"tea"` (3 letters → `e`) in three variables and print the middle character of each, one per line.
+
+::: details Solution
+```python
+word1 = "python"
+word2 = "plov"
+word3 = "tea"
+
+print(word1[len(word1) // 2])
+print(word2[len(word2) // 2])
+print(word3[len(word3) // 2])
+```
+
+```text
+h
+o
+e
+```
+
+- `"python"`: `6 // 2 = 3`, and `word1[3]` is `"h"`.
+- `"plov"`: `4 // 2 = 2`, and `word2[2]` is `"o"`.
+- `"tea"`: `3 // 2 = 1`, and `word3[1]` is `"e"`.
+
+Floor division `//` from the previous lesson gives a whole-number index for any length.
+:::
+
+## Recap
+
+- `+` joins strings and `*` repeats them. Add spaces yourself.
+- `len(text)` counts characters, including spaces.
+- `text[i]` gets one character. Indexes start at `0`, and `-1` is the last character.
+- Strings are **immutable**: build a new string instead of changing one.
+- `"x" in text` checks for a substring and is case-sensitive. Don't `+` a string and a number: use `str()`, commas in `print()`, or an f-string.
+- Every character is a Unicode code point (`ord`/`chr`), and `.encode("utf-8")` turns a `str` into `bytes`.
+
+## Further reading
+
+- [Python Tutorial - Text](https://docs.python.org/3/tutorial/introduction.html#text)
+- [Text sequence type - `str`](https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str)
+- [Common sequence operations](https://docs.python.org/3/library/stdtypes.html#common-sequence-operations)
diff --git a/docs/lessons/02-values-and-variables/04-string-methods-and-slicing.md b/docs/lessons/02-values-and-variables/04-string-methods-and-slicing.md
new file mode 100644
index 0000000..e75ac6b
--- /dev/null
+++ b/docs/lessons/02-values-and-variables/04-string-methods-and-slicing.md
@@ -0,0 +1,531 @@
+---
+title: String Methods and Slicing
+description: "Cut strings with slicing and transform them with methods: changing case, stripping spaces, replacing, splitting, joining, searching, and checking content."
+---
+
+# String Methods and Slicing
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- How to take parts of a string with **slicing**: `text[start:stop:step]`
+- What a **method** is and how to call one
+- The most useful string methods: case, stripping, replacing, searching, splitting, and joining
+- Why methods return a **new** string instead of changing the old one
+- How to chain several methods together
+:::
+
+## Why it matters
+
+Real-world text is messy. Users type `" aziza@EXAMPLE.com "` with extra spaces and odd capitals, file names have extensions to extract, and dates arrive as `"15/09/2026"`. Slicing and string methods are the everyday tools for cleaning text and pulling out the parts you need.
+
+## Slicing: taking part of a string
+
+{.lesson-diagram width=1536 height=1024 loading=lazy}
+
+In the last lesson, `text[i]` got **one** character. A **slice** gets a range of characters:
+
+```text
+text[start:stop]
+```
+
+It starts **at** `start` and goes **up to, but not including,** `stop`.
+
+```text
+ | P | y | t | h | o | n |
+ 0 1 2 3 4 5 6
+ |___________|
+ word[0:3] → "Pyt"
+```
+
+It helps to think of the indexes as sitting **between** the characters. Then `word[0:3]` is everything between position 0 and position 3.
+
+```python
+word = "Python"
+
+print(word[0:3]) # characters 0, 1, 2
+print(word[2:5]) # characters 2, 3, 4
+```
+
+```text
+Pyt
+tho
+```
+
+### Leaving out start or stop
+
+- Leave out `start` to begin at the beginning.
+- Leave out `stop` to go to the end.
+
+```python
+word = "Python"
+
+print(word[:2]) # first 2 characters
+print(word[2:]) # everything from index 2
+print(word[-3:]) # last 3 characters
+print(word[:]) # the whole string
+```
+
+```text
+Py
+thon
+hon
+Python
+```
+
+A handy pattern: `text[:n]` is the first `n` characters, and `text[-n:]` is the last `n`.
+
+### Step
+
+An optional third number is the **step**, how far to move each time:
+
+```python
+digits = "0123456789"
+
+print(digits[::2]) # every 2nd character
+print(digits[1::2]) # every 2nd, starting at index 1
+print(digits[::-1]) # step -1 goes backwards: reversed!
+```
+
+```text
+02468
+13579
+9876543210
+```
+
+`text[::-1]` is the standard Python way to **reverse** a string.
+
+### Slices never raise IndexError
+
+Indexing past the end raises an error, but slicing just stops at the end:
+
+```python
+word = "cat"
+print(word[1:100])
+print(word[5:10])
+```
+
+```text
+at
+
+```
+
+(The second line prints an empty string.)
+
+## What is a method?
+
+A **method** is a function that belongs to a value. You call it with a **dot** after the value:
+
+```text
+value.method_name(arguments)
+```
+
+```python
+name = "aziza"
+print(name.upper())
+print(name.capitalize())
+```
+
+```text
+AZIZA
+Aziza
+```
+
+Compare with the functions you already know: `len(name)` is a regular function that takes the string as an argument, while `name.upper()` is a method called **on** the string.
+
+## Methods return a new string
+
+Strings are immutable (see *Strings*), so string methods **never change** the original. They return a new string:
+
+```python
+name = "aziza"
+name.upper() # creates "AZIZA"... and throws it away
+print(name) # still "aziza"
+
+name = name.upper() # keep the result by assigning it
+print(name)
+```
+
+```text
+aziza
+AZIZA
+```
+
+This is one of the most common beginner bugs, so remember: **if you want to keep the result, assign it.**
+
+## Changing case
+
+| Method | Result for `"hello WORLD"` |
+|---|---|
+| `.upper()` | `"HELLO WORLD"` |
+| `.lower()` | `"hello world"` |
+| `.title()` | `"Hello World"` |
+| `.capitalize()` | `"Hello world"` |
+| `.swapcase()` | `"HELLO world"` |
+
+`.lower()` is especially useful for **comparing** text without caring about capitals:
+
+```python
+answer = "YES"
+print(answer.lower() == "yes")
+```
+
+```text
+True
+```
+
+(`==` checks whether two values are equal. You'll learn it properly in the next module.)
+
+::: warning `.title()` isn't smart about words
+`.title()` capitalizes every letter that follows a non-letter, including an apostrophe or the Uzbek `ʻ`:
+
+```python
+print("don't stop".title())
+print("oʻzbekiston".title())
+```
+
+```text
+Don'T Stop
+OʻZbekiston
+```
+
+For a single name or sentence, `.capitalize()` is often safer.
+:::
+
+## Removing extra spaces: strip
+
+User input often has spaces or newlines around it. `.strip()` removes whitespace from **both ends**, but not from the middle:
+
+```python
+raw = " Tashkent \n"
+
+print("[" + raw.strip() + "]")
+print("[" + raw.lstrip() + "]") # left side only
+print("[" + raw.rstrip() + "]") # right side only
+```
+
+```text
+[Tashkent]
+[Tashkent
+]
+[ Tashkent]
+```
+
+You can also strip specific characters: `"***sale***".strip("*")` gives `"sale"`.
+
+### Removing a prefix or suffix
+
+`.strip(".txt")` does **not** remove the text `".txt"`. It removes any of the characters `.`, `t` and `x` from both ends, so `"test.txt".strip(".txt")` gives `"es"`. To remove an exact piece from the start or the end, use `.removeprefix()` or `.removesuffix()`. They leave the string unchanged if the piece isn't there:
+
+```python
+photo = "IMG_2026.jpg"
+
+print(photo.removeprefix("IMG_"))
+print(photo.removesuffix(".jpg"))
+print(photo.removesuffix(".png"))
+```
+
+```text
+2026.jpg
+IMG_2026
+IMG_2026.jpg
+```
+
+## Replacing text
+
+`.replace(old, new)` replaces **every** occurrence:
+
+```python
+date = "15/09/2026"
+print(date.replace("/", "-"))
+
+sentence = "I like tea. Tea is great."
+print(sentence.replace("tea", "coffee")) # case-sensitive!
+```
+
+```text
+15-09-2026
+I like coffee. Tea is great.
+```
+
+## Searching
+
+```python
+text = "banana bread and banana milk"
+
+print(text.count("banana")) # how many times
+print(text.find("bread")) # index of first match
+print(text.find("apple")) # -1 means not found
+print(text.startswith("banana"))
+print(text.endswith("milk"))
+```
+
+```text
+2
+7
+-1
+True
+True
+```
+
+- `.find()` returns `-1` if the text isn't there.
+- `.index()` does the same job but raises a `ValueError` when the text isn't found.
+- If you only need yes or no, `"bread" in text` is simpler.
+
+## Splitting and joining
+
+`.split()` breaks a string into a **list** of pieces. With no argument, it splits on any whitespace:
+
+```python
+sentence = "Python is really fun"
+words = sentence.split()
+print(words)
+print(len(words))
+```
+
+```text
+['Python', 'is', 'really', 'fun']
+4
+```
+
+Give it a separator to split on something else:
+
+```python
+date = "15/09/2026"
+parts = date.split("/")
+print(parts)
+print(parts[2]) # the year
+```
+
+```text
+['15', '09', '2026']
+2026
+```
+
+Add a second argument, `maxsplit`, to stop after that many splits. The rest stays in one piece:
+
+```python
+line = "Tashkent: capital: 3 million"
+print(line.split(":", 1))
+```
+
+```text
+['Tashkent', ' capital: 3 million']
+```
+
+The square-bracket result is a **list**. You'll study lists in the *Collections* module. For now, you can get items from it with an index, just like characters in a string.
+
+`.join()` does the opposite: it glues pieces together, with the string you call it on **between** them:
+
+```python
+parts = ["15", "09", "2026"]
+print("-".join(parts))
+print(" | ".join(["tea", "coffee", "juice"]))
+```
+
+```text
+15-09-2026
+tea | coffee | juice
+```
+
+A split-then-join combination is a neat way to **normalize spaces**:
+
+```python
+messy = "too many spaces"
+print(" ".join(messy.split()))
+```
+
+```text
+too many spaces
+```
+
+## Checking what's inside
+
+These methods return `True` or `False`:
+
+| Method | True when… | `"2026"` | `"abc"` | `"abc1"` |
+|---|---|---|---|---|
+| `.isdigit()` | all characters are digits | `True` | `False` | `False` |
+| `.isalpha()` | all characters are letters | `False` | `True` | `False` |
+| `.isalnum()` | all characters are letters or digits | `True` | `True` | `True` |
+| `.isupper()` / `.islower()` | all letters are upper/lower case | `False` | `False` / `True` | `False` / `True` |
+| `.isspace()` | all characters are whitespace | `False` | `False` | `False` |
+
+All of them return `False` for an empty string `""`.
+
+`.isdigit()` isn't a full "is this a number?" check. It's `False` for `"-5"` and `"3.5"`, because `-` and `.` aren't digits. It's also `True` for some characters that `int()` rejects, such as `"²"`.
+
+## Chaining methods
+
+Because each method returns a string, you can call another method on the result, one after another:
+
+```python
+raw_email = " Aziza.Karimova@EXAMPLE.com "
+
+email = raw_email.strip().lower()
+print(email)
+
+username = email.split("@")[0]
+print(username.replace(".", " ").title())
+```
+
+```text
+aziza.karimova@example.com
+Aziza Karimova
+```
+
+Read chains from left to right: strip → lowercase → split at `@` → take the first part.
+
+## Try it
+
+Clean up the messy input and print a tidy greeting. Then try changing `raw_name` to something even messier.
+
+
+
+## Common mistakes
+
+### 1. Not saving the result
+
+```python
+city = "tashkent"
+city.capitalize()
+print(city) # still "tashkent"
+```
+
+**Fix:** `city = city.capitalize()`.
+
+### 2. Forgetting the parentheses
+
+```python
+name = "aziza"
+print(name.upper)
+```
+
+```text
+
+```
+
+Without `()` you get the method itself, not its result. **Fix:** `name.upper()`.
+
+### 3. Off-by-one slices
+
+```python
+code = "UZ-2026"
+print(code[0:1]) # "U", not "UZ"
+```
+
+The stop index is **not included**. **Fix:** `code[0:2]`, or simply `code[:2]`.
+
+### 4. `.index()` on missing text
+
+```py
+print("hello".index("z"))
+```
+
+```text
+ValueError: substring not found
+```
+
+**Fix:** use `.find()`, which returns `-1`, or check with `in` first.
+
+## Practice
+
+### 1. File extension
+
+For `filename = "report_final.pdf"`, print the extension `pdf` using `.split()`.
+
+::: details Solution
+```python
+filename = "report_final.pdf"
+print(filename.split(".")[-1])
+```
+
+`[-1]` takes the last piece, so it also works for names like `"archive.tar.gz"` (giving `gz`). A name with no dot, like `"README"`, has only one piece, so you get the whole name back.
+:::
+
+### 2. Tidy name
+
+Turn `" dILNOZA "` into `"Dilnoza"`.
+
+::: details Solution
+```python
+raw = " dILNOZA "
+print(raw.strip().capitalize())
+```
+:::
+
+### 3. Phone number format
+
+Given `phone = "998901234567"`, use slicing to print `+998 (90) 123-45-67`.
+
+::: details Solution
+```python
+phone = "998901234567"
+
+formatted = ("+" + phone[:3] + " (" + phone[3:5] + ") "
+ + phone[5:8] + "-" + phone[8:10] + "-" + phone[10:])
+print(formatted)
+```
+
+Wrapping the expression in parentheses lets it continue on the next line.
+:::
+
+### 4. Word stats
+
+For `text = "the quick brown fox jumps over the lazy dog"`, print:
+
+1. the number of words,
+2. how many times `"the"` appears as text,
+3. the sentence with each word capitalized,
+4. the sentence reversed.
+
+::: details Solution
+```python
+text = "the quick brown fox jumps over the lazy dog"
+
+print(len(text.split()))
+print(text.count("the"))
+print(text.title())
+print(text[::-1])
+```
+
+```text
+9
+2
+The Quick Brown Fox Jumps Over The Lazy Dog
+god yzal eht revo spmuj xof nworb kciuq eht
+```
+:::
+
+### 5. Mask an email
+
+Hide most of the username in an email: keep the first **2** characters of the username, replace the rest with `*` (keeping the same length), and keep the domain. For `"aziza.karimova@example.com"`, print `az************@example.com`.
+
+::: details Solution
+```python
+email = "aziza.karimova@example.com"
+
+at = email.find("@")
+username = email[:at]
+domain = email[at:] # includes the "@"
+
+masked = username[:2] + "*" * (len(username) - 2) + domain
+print(masked)
+```
+
+`email.split("@")` would also work to separate the two parts.
+:::
+
+## Recap
+
+- `text[start:stop:step]` slices a string. `stop` is excluded, missing values mean "from the start" or "to the end", and `[::-1]` reverses.
+- Slices never raise `IndexError`.
+- Methods are called with a dot: `text.method()`. String methods return a **new** string, so assign the result to keep it.
+- Case: `upper`, `lower`, `title`, `capitalize`. Cleaning: `strip`, `replace`, `removeprefix`, `removesuffix`.
+- Searching: `count`, `find` (−1 if missing), `index` (error if missing), `startswith`, `endswith`.
+- `split(sep, maxsplit)` turns a string into a list of pieces, and `"sep".join(pieces)` glues them back together.
+
+## Further reading
+
+- [String methods](https://docs.python.org/3/library/stdtypes.html#string-methods)
+- [Python Tutorial - Text (indexing and slicing)](https://docs.python.org/3/tutorial/introduction.html#text)
diff --git a/docs/lessons/02-values-and-variables/05-f-strings.md b/docs/lessons/02-values-and-variables/05-f-strings.md
new file mode 100644
index 0000000..47372c6
--- /dev/null
+++ b/docs/lessons/02-values-and-variables/05-f-strings.md
@@ -0,0 +1,475 @@
+---
+title: F-Strings
+description: "Build readable text with f-strings: inserting variables and expressions, formatting decimals, thousands separators, percentages, alignment, and the = debugging shortcut."
+---
+
+# F-Strings
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- How to put values inside text with `f"...{value}..."`
+- How to use expressions and method calls inside `{}`
+- How to format numbers: decimal places, thousands separators, percentages, and padding
+- How to line up text in columns
+- The `{value=}` and `!r` shortcuts for debugging
+:::
+
+## Why it matters
+
+Programs constantly build text from data: `"Hello, Aziza!"`, `"Total: 125,000.00 som"`, `"Progress: 75%"`. Joining pieces with `+` and `str()` gets messy fast. **F-strings** (formatted string literals) are the modern, readable way to do it, and they're what you'll see in almost all current Python code.
+
+## The basics
+
+Put an `f` right before the opening quote, then write any value inside **curly braces** `{}`:
+
+```python
+name = "Aziza"
+age = 20
+
+print(f"My name is {name} and I am {age} years old.")
+```
+
+```text
+My name is Aziza and I am 20 years old.
+```
+
+Compare the alternatives:
+
+```python
+name = "Aziza"
+age = 20
+
+print("My name is " + name + " and I am " + str(age) + " years old.") # concatenation
+print("My name is", name, "and I am", age, "years old.") # print arguments
+print(f"My name is {name} and I am {age} years old.") # f-string
+```
+
+The f-string reads like the final sentence. You don't need `str()` and you don't need to manage spaces.
+
+::: warning Don't forget the `f`
+Without the `f`, the braces are just ordinary characters: `"Hello, {name}"` prints `Hello, {name}`.
+:::
+
+## Expressions inside braces
+
+The braces can hold any **expression**, meaning anything that produces a value, not just a variable name:
+
+```python
+price = 12500
+quantity = 3
+name = "dilnoza"
+
+print(f"Total: {price * quantity}")
+print(f"Hello, {name.title()}!")
+print(f"Your name has {len(name)} letters.")
+```
+
+```text
+Total: 37500
+Hello, Dilnoza!
+Your name has 7 letters.
+```
+
+Keep the expressions short. If a calculation is complicated, store it in a variable first and put the variable in the f-string.
+
+### Quotes inside braces
+
+If you call a method with a string argument inside an f-string, use the **other kind of quote** inside:
+
+```python
+city = "Tashkent"
+print(f"{city.replace('a', 'A')}")
+```
+
+```text
+TAshkent
+```
+
+Python 3.12 and newer also allow the same quotes inside, but using the other kind works in every version and is easier to read.
+
+## Formatting numbers
+
+After the value, add a colon `:` and a **format specification** to control how it's displayed:
+
+```text
+{value:format_spec}
+```
+
+### Decimal places: `.2f`
+
+```python
+pi = 3.14159265
+price = 7.5
+
+print(f"{pi:.2f}")
+print(f"{pi:.4f}")
+print(f"{price:.2f}")
+```
+
+```text
+3.14
+3.1416
+7.50
+```
+
+`.2f` means "a float with 2 digits after the decimal point". It **rounds** for display without changing the variable. This also hides floating-point noise:
+
+```python
+total = 0.1 + 0.2
+print(f"{total:.2f}")
+```
+
+```text
+0.30
+```
+
+### Thousands separators: `,` or `_`
+
+```python
+population = 37543000
+salary = 8250000.5
+
+print(f"{population:,}")
+print(f"{salary:,.2f}")
+print(f"{population:_}")
+```
+
+```text
+37,543,000
+8,250,000.50
+37_543_000
+```
+
+If you need spaces as separators, which is common in Uzbekistan and much of Europe, format with `,` and then replace: `f"{population:,}".replace(",", " ")` gives `37 543 000`.
+
+### Percentages: `%`
+
+`%` multiplies by 100 and adds a percent sign. Like `f`, it shows 6 decimal places unless you give a precision, so `{0.756:%}` gives `75.600000%`. Add one such as `.1%` or `.0%`:
+
+```python
+done = 0.756
+print(f"Progress: {done:.1%}")
+print(f"Progress: {done:.0%}")
+```
+
+```text
+Progress: 75.6%
+Progress: 76%
+```
+
+### Leading zeros: `05d` or `02d`
+
+```python
+order = 42
+hour, minute = 9, 5
+
+print(f"Order #{order:05d}")
+print(f"Time: {hour:02d}:{minute:02d}")
+```
+
+```text
+Order #00042
+Time: 09:05
+```
+
+`d` means a whole number (*decimal integer*), and `05` means "at least 5 characters wide, padded with zeros".
+
+## Alignment and width
+
+Give a **width** to reserve space, and a direction to align within it:
+
+| Spec | Meaning |
+|---|---|
+| `<10` | left-align in 10 characters |
+| `>10` | right-align in 10 characters |
+| `^10` | center in 10 characters |
+| `*^10` | center, filling the space with `*` |
+
+```python
+print(f"|{'tea':<10}|")
+print(f"|{'tea':>10}|")
+print(f"|{'tea':^10}|")
+print(f"|{'tea':*^10}|")
+```
+
+```text
+|tea |
+| tea|
+| tea |
+|***tea****|
+```
+
+Width and number formats combine. The width comes first, then the precision:
+
+```python
+item1, price1 = "Green tea", 3500
+item2, price2 = "Samsa", 12000
+item3, price3 = "Lemonade", 9500.5
+
+print(f"{'Item':<12}{'Price':>12}")
+print("-" * 24)
+print(f"{item1:<12}{price1:>12,.2f}")
+print(f"{item2:<12}{price2:>12,.2f}")
+print(f"{item3:<12}{price3:>12,.2f}")
+```
+
+```text
+Item Price
+------------------------
+Green tea 3,500.00
+Samsa 12,000.00
+Lemonade 9,500.50
+```
+
+Numbers are right-aligned by default and text is left-aligned, but being explicit makes tables predictable.
+
+## Debugging with `=`
+
+Add `=` after an expression to print **both** the expression and its value. It's perfect for checking what's going on in your code:
+
+```python
+width = 4
+height = 2.5
+
+print(f"{width=}")
+print(f"{width * height=}")
+print(f"{height = :.2f}")
+```
+
+```text
+width=4
+width * height=10.0
+height = 2.50
+```
+
+### Seeing hidden spaces: `!r`
+
+Add `!r` to show a value the way Python writes it in code, with quotes around strings. Extra spaces become easy to spot. The `=` form does this for strings automatically:
+
+```python
+raw = " Aziza "
+
+print(f"Name: {raw}.")
+print(f"Name: {raw!r}")
+print(f"{raw=}")
+```
+
+```text
+Name: Aziza .
+Name: ' Aziza '
+raw=' Aziza '
+```
+
+## Literal braces
+
+To show a real `{` or `}`, double it:
+
+```python
+name = "set"
+print(f"A {name} looks like {{1, 2, 3}}")
+```
+
+```text
+A set looks like {1, 2, 3}
+```
+
+::: info Older styles you'll see
+Tutorials, Stack Overflow answers and older code often use two earlier ways of formatting. **Read them, but write f-strings.**
+
+```python
+name = "Aziza"
+price = 12.5
+
+print("Hello, {}! Total: {:.2f}".format(name, price)) # str.format()
+print("Hello, %s! Total: %.2f" % (name, price)) # % formatting
+```
+
+```text
+Hello, Aziza! Total: 12.50
+Hello, Aziza! Total: 12.50
+```
+
+The `{:.2f}` in `.format()` uses the same format specs you learned above. In `%` formatting, `%s` stands for a string and `%.2f` for a float with 2 decimals.
+:::
+
+## Try it
+
+Change the values and the format specs. Try `:.0f`, `:>15,`, or `:.1%`.
+
+
+
+## Common mistakes
+
+### 1. Missing `f`
+
+```python
+name = "Bekzod"
+print("Hello, {name}!")
+```
+
+```text
+Hello, {name}!
+```
+
+**Fix:** `f"Hello, {name}!"`.
+
+### 2. Format spec on the wrong type
+
+```py
+code = "42"
+print(f"{code:.2f}")
+```
+
+```text
+ValueError: Unknown format code 'f' for object of type 'str'
+```
+
+`.2f` only works on numbers, and `"42"` is a string. **Fix:** convert first with `float(code)`, which you'll learn in the next lesson.
+
+### 3. A space before the colon
+
+```python
+price = 5
+print(f"{price :.2f}") # works, but hard to read
+```
+
+It runs, but convention is `{price:.2f}` with no spaces. The one exception is the `=` debugging form, where spaces are kept in the output on purpose.
+
+### 4. Formatting too early
+
+```python
+price = 12.5
+total = f"{price:.2f}"
+print(total * 2)
+```
+
+```text
+12.5012.50
+```
+
+`f"{price:.2f}"` produces **text**, so `* 2` repeats the string instead of doubling the number. **Fix:** keep numbers as numbers for calculations (`total = price * 2`) and format only when printing: `print(f"{total:.2f}")`.
+
+## Practice
+
+### 1. Introduction
+
+With `name = "Kamola"`, `city = "Namangan"`, and `year = 2003`, print `Kamola from Namangan was born in 2003.` using one f-string.
+
+::: details Solution
+```python
+name = "Kamola"
+city = "Namangan"
+year = 2003
+print(f"{name} from {city} was born in {year}.")
+```
+:::
+
+### 2. Two decimals
+
+Print the average of `87`, `92`, and `78` with exactly two decimal places: `Average: 85.67`.
+
+::: details Solution
+```python
+average = (87 + 92 + 78) / 3
+print(f"Average: {average:.2f}")
+```
+:::
+
+### 3. Big numbers
+
+A company earned `1234567890.456` som. Print it three ways:
+
+1. with comma separators and 2 decimals,
+2. with space separators and no decimals,
+3. in millions with 1 decimal, like `1234.6 million`.
+
+::: details Solution
+```python
+revenue = 1234567890.456
+
+print(f"{revenue:,.2f}")
+print(f"{revenue:,.0f}".replace(",", " "))
+print(f"{revenue / 1_000_000:.1f} million")
+```
+
+```text
+1,234,567,890.46
+1 234 567 890
+1234.6 million
+```
+:::
+
+### 4. Progress bar
+
+Given `done = 7` and `total = 20`, print a progress bar 20 characters wide, with `#` for done and `.` for remaining, followed by the percentage:
+
+```text
+[#######.............] 35%
+```
+
+::: details Solution
+```python
+done = 7
+total = 20
+
+bar = "#" * done + "." * (total - done)
+print(f"[{bar}] {done / total:.0%}")
+```
+:::
+
+### 5. Receipt
+
+Print this receipt with f-strings, so every price lines up on the right. Calculate the subtotal, 12% VAT, and the total from the item prices.
+
+```text
+==============================
+Plov x2 90,000.00
+Green tea x3 10,500.00
+Non x4 16,000.00
+------------------------------
+Subtotal 116,500.00
+VAT 12% 13,980.00
+TOTAL 130,480.00
+==============================
+```
+
+::: details Solution
+```python
+plov = 2 * 45000
+tea = 3 * 3500
+non = 4 * 4000
+
+subtotal = plov + tea + non
+vat = subtotal * 0.12
+total = subtotal + vat
+
+width = 30
+print("=" * width)
+print(f"{'Plov x2':<16}{plov:>14,.2f}")
+print(f"{'Green tea x3':<16}{tea:>14,.2f}")
+print(f"{'Non x4':<16}{non:>14,.2f}")
+print("-" * width)
+print(f"{'Subtotal':<16}{subtotal:>14,.2f}")
+print(f"{'VAT 12%':<16}{vat:>14,.2f}")
+print(f"{'TOTAL':<16}{total:>14,.2f}")
+print("=" * width)
+```
+
+The label column is 16 characters and the price column is 14, so each line is exactly 30 characters, matching the border.
+:::
+
+## Recap
+
+- Write `f"...{expression}..."` to put values into text. Don't forget the `f`.
+- Anything that produces a value can go inside `{}`: variables, math, or method calls.
+- `{x:.2f}` sets decimal places, `{x:,}` adds thousands separators, and `{x:.1%}` shows a percentage.
+- `{x:05d}` pads with zeros. `<`, `>`, and `^` with a width align text in columns.
+- `{x=}` prints the expression and its value, `{x!r}` shows quotes and hidden spaces, and {{ }} prints literal braces.
+- Format for **display**, and keep numbers as numbers for calculations.
+
+## Further reading
+
+- [Python Tutorial - Formatted string literals](https://docs.python.org/3/tutorial/inputoutput.html#formatted-string-literals)
+- [Format specification mini-language](https://docs.python.org/3/library/string.html#format-specification-mini-language)
+- [Lexical analysis - f-strings](https://docs.python.org/3/reference/lexical_analysis.html#f-strings)
diff --git a/docs/lessons/02-values-and-variables/06-type-conversion-and-input.md b/docs/lessons/02-values-and-variables/06-type-conversion-and-input.md
new file mode 100644
index 0000000..410fb29
--- /dev/null
+++ b/docs/lessons/02-values-and-variables/06-type-conversion-and-input.md
@@ -0,0 +1,394 @@
+---
+title: Input and Type Conversion
+description: "Make interactive programs with input(), clean the answers, and convert between strings, integers, and floats with int(), float(), and str()."
+---
+
+# Input and Type Conversion
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- How to ask the user for information with `input()`
+- Why `input()` always gives you a **string**
+- How to convert values with `int()`, `float()`, and `str()`
+- What happens when a conversion fails, including decimal commas like `12,5`
+- How to clean text answers and build small interactive programs
+:::
+
+## Why it matters
+
+So far, every value in your programs was written directly in the code. Real programs respond to their users: a calculator needs numbers, a quiz needs answers, a sign-up form needs a name. `input()` lets your program **ask**, and type conversion lets you turn the answers into data you can calculate with.
+
+## Asking for input
+
+`input()` shows a message (the **prompt**), waits for the user to type something and press Enter, and returns what they typed:
+
+```python
+name = input("What is your name? ")
+print(f"Nice to meet you, {name}!")
+```
+
+```text
+What is your name? Aziza
+Nice to meet you, Aziza!
+```
+
+End the prompt with a space so the user's typing doesn't stick to your question.
+
+::: info Running input() on this site
+In the browser editors, there's no live keyboard input. Type your answers **in advance** in the **Values for input()** box, one per line. Each call to `input()` uses the next line.
+:::
+
+## `input()` always returns a string
+
+Even if the user types a number, you get **text**:
+
+```python
+age = input("How old are you? ")
+print(type(age))
+```
+
+```text
+How old are you? 20
+
+```
+
+That's a problem as soon as you try to do math:
+
+```py
+age = input("How old are you? ")
+print(age + 1)
+```
+
+```text
+TypeError: can only concatenate str (not "int") to str
+```
+
+And sometimes it's worse, because there's no error, just a wrong answer:
+
+```python
+a = "5"
+b = "3"
+print(a + b) # "53", not 8
+```
+
+The fix is to **convert** the string to a number.
+
+## Cleaning text answers: `.strip()`
+
+Users often type a stray space before or after their answer. You can't see it, but Python can, and the answer no longer matches:
+
+```python
+city = input("City: ") # the user types " Samarkand "
+print(city == "Samarkand")
+
+city = city.strip()
+print(city == "Samarkand")
+```
+
+```text
+City: Samarkand
+False
+True
+```
+
+For text answers, it's a good habit to call `.strip()` straight away, and to chain `.lower()` or `.title()` if capitals don't matter:
+
+```python
+city = input("City: ").strip().title() # the user types " samarkand "
+print(f"Welcome to {city}!")
+```
+
+```text
+City: samarkand
+Welcome to Samarkand!
+```
+
+## Converting types
+
+| Function | Converts to | Example | Result |
+|---|---|---|---|
+| `int()` | whole number | `int("42")` | `42` |
+| `float()` | decimal number | `float("3.5")` | `3.5` |
+| `str()` | string | `str(42)` | `"42"` |
+
+```python
+age_text = "20"
+age = int(age_text)
+
+print(age + 1)
+print(type(age))
+```
+
+```text
+21
+
+```
+
+Usually you convert **right away**, by wrapping `input()` inside `int()` or `float()`:
+
+```python
+age = int(input("How old are you? "))
+print(f"Next year you will be {age + 1}.")
+```
+
+Python runs the inside first: `input()` returns a string, then `int()` converts it.
+
+### `int()` vs `float()`
+
+Use `int()` for things that are always whole (age, count, year) and `float()` for things that can have decimals (price, weight, temperature):
+
+```python
+weight = float(input("Weight in kg: "))
+height = float(input("Height in meters: "))
+
+bmi = weight / height ** 2
+print(f"BMI: {bmi:.1f}")
+```
+
+### More conversions
+
+```python
+print(int(3.99)) # float → int cuts off the decimals (no rounding)
+print(round(3.99)) # use round() if you want rounding
+print(float(7)) # int → float
+print(int(" 42 ")) # surrounding spaces are OK
+print(int("-15")) # a minus sign is OK
+print(str(3.5) + "kg") # number → string, to join with text
+```
+
+```text
+3
+4
+7.0
+42
+-15
+3.5kg
+```
+
+## When conversion fails
+
+If the text doesn't look like a number of the right kind, Python raises a `ValueError`:
+
+```py
+int("twenty")
+```
+
+```text
+ValueError: invalid literal for int() with base 10: 'twenty'
+```
+
+Some cases surprise beginners:
+
+| Expression | Result |
+|---|---|
+| `int("3.5")` | `ValueError`: `int()` doesn't accept a decimal point in text |
+| `int(float("3.5"))` | `3`: convert to float first, then int |
+| `int("")` | `ValueError`: the user just pressed Enter |
+| `int("1,000")` | `ValueError`: commas aren't allowed |
+| `float("1e3")` | `1000.0`: scientific notation is accepted |
+| `float("12,5")` | `ValueError`: the decimal point must be a dot |
+
+The last row matters in Uzbekistan and much of Europe, where people often write decimals with a comma. The error message for `float()` is worded a little differently from the `int()` one:
+
+```py
+float("12,5")
+```
+
+```text
+ValueError: could not convert string to float: '12,5'
+```
+
+If your users may type a comma, replace it before converting:
+
+```python
+weight_text = "12,5"
+weight = float(weight_text.replace(",", "."))
+print(weight)
+```
+
+```text
+12.5
+```
+
+For now, assume users type valid numbers. In the *Errors and Files* module you'll learn to catch these errors and ask again.
+
+## Putting it together
+
+A small, complete interactive program:
+
+```python
+print("=== Tip calculator ===")
+
+bill = float(input("Bill amount: "))
+tip_percent = int(input("Tip percent: "))
+people = int(input("Number of people: "))
+
+tip = bill * tip_percent / 100
+total = bill + tip
+per_person = total / people
+
+print(f"Tip: {tip:,.2f}")
+print(f"Total: {total:,.2f}")
+print(f"Per person: {per_person:,.2f}")
+```
+
+Run it with the values `150000`, `10`, and `4`:
+
+```text
+=== Tip calculator ===
+Bill amount: 150000
+Tip percent: 10
+Number of people: 4
+Tip: 15,000.00
+Total: 165,000.00
+Per person: 41,250.00
+```
+
+The shape of this program is very common: **input → convert → calculate → output**.
+
+## Try it
+
+Type two numbers into **Values for input()** (one per line), then run the program.
+
+
+
+## Common mistakes
+
+### 1. Doing math on input without converting
+
+```python
+price = input("Price: ") # the user types 50
+print(price * 2)
+```
+
+```text
+Price: 50
+5050
+```
+
+No error, just a wrong answer: a string times `2` repeats the string. **Fix:** convert when you read the value: `price = float(input("Price: "))`.
+
+### 2. Using `int()` for decimal input
+
+```py
+price = int(input("Price: ")) # user types 12.5
+```
+
+```text
+ValueError: invalid literal for int() with base 10: '12.5'
+```
+
+**Fix:** use `float()` when the value can have decimals.
+
+### 3. Typing a decimal comma
+
+```py
+weight = float(input("Weight in kg: ")) # user types 12,5
+```
+
+```text
+ValueError: could not convert string to float: '12,5'
+```
+
+**Fix:** tell users to type a dot, or accept both with `float(input("Weight in kg: ").replace(",", "."))`.
+
+### 4. Forgetting the space in the prompt
+
+```python
+name = input("Name:") # the user types Aziza
+```
+
+```text
+Name:Aziza
+```
+
+The typed text runs into the prompt. **Fix:** end the prompt with a space: `input("Name: ")`.
+
+## Practice
+
+### 1. Echo
+
+Ask for the user's favorite food and print ` is delicious!`, with the food in uppercase.
+
+::: details Solution
+```python
+food = input("Favorite food? ")
+print(f"{food.upper()} is delicious!")
+```
+:::
+
+### 2. Birth year
+
+Ask for the user's age and print the year they were born, assuming the current year is `2026` and their birthday has already passed this year.
+
+::: details Solution
+```python
+age = int(input("Your age: "))
+print(f"You were born in {2026 - age}.")
+```
+:::
+
+### 3. Unit converter
+
+Ask for a distance in kilometers (it can have decimals) and print it in miles with 2 decimals. 1 km = 0.621371 miles.
+
+::: details Solution
+```python
+km = float(input("Kilometers: "))
+miles = km * 0.621371
+print(f"{km} km = {miles:.2f} miles")
+```
+:::
+
+### 4. Predict the output
+
+Without running it, what does each line print? One of them raises an error: which one, and why?
+
+```py
+print(int("8") + 2)
+print("8" + str(2))
+print(int(9.9))
+print(float("2") * 3)
+print(int("9.9"))
+```
+
+::: details Solution
+1. `10`
+2. `82`: string joining
+3. `9`: `int()` cuts off the decimals
+4. `6.0`
+5. `ValueError`: `int()` can't convert a string that contains a decimal point. Use `int(float("9.9"))` instead.
+:::
+
+### 5. Time until
+
+Ask for a number of minutes (a whole number) and print it as days, hours, and minutes, like `1 days, 2 hours, 5 minutes` for `1565`.
+
+::: details Solution
+```python
+total = int(input("Minutes: "))
+
+days = total // (24 * 60)
+remaining = total % (24 * 60)
+hours = remaining // 60
+minutes = remaining % 60
+
+print(f"{days} days, {hours} hours, {minutes} minutes")
+```
+
+This combines `input`, `int`, `//`, `%`, and f-strings. You'll learn to write "1 day" instead of "1 days" with `if` in the next module.
+:::
+
+## Recap
+
+- `input("prompt ")` waits for the user and returns what they typed **as a string**.
+- Convert with `int()`, `float()`, and `str()`. Convert right away: `int(input(...))`.
+- `int(3.9)` cuts off decimals. Use `round()` to round.
+- Invalid text like `int("3.5")`, `int("abc")` or `float("12,5")` raises a `ValueError`. Use `.replace(",", ".")` for decimal commas, and `.strip()` on text answers.
+- A common program shape is **input → convert → calculate → output**.
+
+## Further reading
+
+- [Built-in functions - `input()`](https://docs.python.org/3/library/functions.html#input)
+- [Built-in functions - `int()`](https://docs.python.org/3/library/functions.html#int) and [`float()`](https://docs.python.org/3/library/functions.html#float)
diff --git a/docs/lessons/02-values-and-variables/07-reading-errors-and-debugging.md b/docs/lessons/02-values-and-variables/07-reading-errors-and-debugging.md
new file mode 100644
index 0000000..29ae1a3
--- /dev/null
+++ b/docs/lessons/02-values-and-variables/07-reading-errors-and-debugging.md
@@ -0,0 +1,386 @@
+---
+title: Reading Errors and Debugging
+description: "Understand Python error messages, recognize the most common error types, and use a simple, reliable process to find and fix bugs."
+---
+
+# Reading Errors and Debugging
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- How to read a **traceback**, and which line to look at first
+- The difference between syntax errors and runtime errors
+- The most common error types and what usually causes them
+- **Logic errors**: bugs with no error message
+- A step-by-step debugging process you can use for any problem
+:::
+
+## Why it matters
+
+Every programmer writes bugs every day. Experienced programmers don't make fewer mistakes, they **find them faster**. Python's error messages are detailed and often suggest the fix, and learning to read them turns a scary wall of red text into a helpful note.
+
+## Anatomy of an error message
+
+{.lesson-diagram width=1536 height=1024 loading=lazy}
+
+Save this as `shop.py` and run it:
+
+```py
+price = 25000
+quantity = input("How many? ")
+total = price * quantity + delivery
+print(total)
+```
+
+After typing `3`, you get:
+
+```text
+Traceback (most recent call last):
+ File "shop.py", line 3, in
+ total = price * quantity + delivery
+ ^^^^^^^^
+NameError: name 'delivery' is not defined
+```
+
+Read it **from the bottom up**:
+
+| Part | What it tells you |
+|---|---|
+| `NameError` | The **type** of error |
+| `name 'delivery' is not defined` | The **message**: what exactly went wrong |
+| `^^^^^^^^` | **Where** on the line the problem is |
+| `total = price * quantity + delivery` | The line of code that failed |
+| `File "shop.py", line 3` | The **file and line number**. On your computer you'll see the full path, such as `File "/home/aziza/shop.py"` |
+| `Traceback (most recent call last)` | The heading. Later, when functions call other functions, this lists every step |
+
+**Rule 1: read the last line first.** It usually tells you what's wrong.
+
+Fix that line by defining `delivery = 5000` before it, and run again:
+
+```text
+TypeError: can only concatenate str (not "int") to str
+```
+
+Progress! `quantity` is a string, because `input()` returns text. `price * quantity` didn't fail (a number times a string **repeats** it), but adding `delivery` did. The failing line isn't always the mistake: the cause is on line 2, and the fix is `quantity = int(input("How many? "))`.
+
+## Two kinds of errors
+
+### Syntax errors: Python can't read your code
+
+Python checks the grammar of the **whole file before running anything**. If something is malformed, nothing runs at all:
+
+```py
+print("Start")
+print("Hello"
+print("End")
+```
+
+```text
+ File "demo.py", line 2
+ print("Hello"
+ ^
+SyntaxError: '(' was never closed
+```
+
+Notice that `Start` was never printed. Since 3.10, Python reports an unclosed bracket on the line where it was **opened**, and an unclosed string on its own line. If the message is only a plain `invalid syntax` and the reported line looks fine, check the line above it too.
+
+`IndentationError` and `TabError` are special kinds of syntax error.
+
+### Runtime errors (exceptions): something went wrong while running
+
+The grammar was fine, but a line failed while it was running. Everything **before** that line already ran:
+
+```py
+print("Start")
+print(10 / 0)
+print("End")
+```
+
+```text
+Start
+Traceback (most recent call last):
+ File "demo.py", line 2, in
+ print(10 / 0)
+ ~~~^~~
+ZeroDivisionError: division by zero
+```
+
+## The errors you'll see most
+
+| Error | Typical cause | Example |
+|---|---|---|
+| `SyntaxError` | Missing `)`, `"`, or `:`; typo in a keyword | `print("hi"` |
+| `IndentationError` | Wrong or missing indentation | a line indented for no reason |
+| `NameError` | Variable not defined yet, or misspelled | `print(totl)` |
+| `TypeError` | Operation on the wrong type | `"Age: " + 20` |
+| `ValueError` | Right type, unacceptable value | `int("abc")` |
+| `ZeroDivisionError` | Dividing by zero | `5 / 0` |
+| `IndexError` | Index past the end | `"cat"[5]` |
+| `AttributeError` | Method doesn't exist for that type | `(42).upper()` |
+
+Python's messages often include a suggestion. Read it:
+
+```text
+NameError: name 'pirnt' is not defined. Did you mean: 'print'?
+```
+
+```text
+SyntaxError: invalid syntax. Perhaps you forgot a comma?
+```
+
+## Logic errors: the silent bugs
+
+The hardest bugs produce **no error at all**. The program runs, but gives the wrong answer:
+
+```python
+score1 = 80
+score2 = 90
+average = score1 + score2 / 2 # should be (score1 + score2) / 2
+print(f"Average: {average}")
+```
+
+```text
+Average: 125.0
+```
+
+Python did exactly what you wrote. To catch logic errors, **know what the right answer should be** and check it. That's why this course keeps asking you to predict output before running.
+
+## A debugging process
+
+When something is wrong, follow these steps instead of changing code randomly.
+
+### 1. Read the error message carefully
+
+Start with the last line: the error type and message. Then look at the line number and the `^` markers. For a plain `invalid syntax` on a line that looks fine, check the line above too.
+
+### 2. Reproduce it reliably
+
+Find the exact input that causes the problem. "It fails when I type `12.5`" is much easier to fix than "it sometimes breaks".
+
+### 3. Check your assumptions with `print()`
+
+Most bugs come from a variable not holding what you think it holds. Print values and types at key points:
+
+```python
+quantity = "3" # imagine this came from input()
+price = 25000
+
+print(f"{quantity=}, {type(quantity)=}") # debugging line
+total = price * int(quantity)
+print(f"{total=}") # debugging line
+```
+
+```text
+quantity='3', type(quantity)=
+total=75000
+```
+
+The `=` form from the *F-Strings* lesson is ideal here. **Remove debugging prints** when you're done.
+
+::: tip Step through with a debugger
+A **debugger** runs your program one line at a time and shows every variable as it changes. In Thonny, click **Debug** (the bug icon) instead of Run, then press **F7** to step. In VS Code, click left of a line number to set a **breakpoint**, then press **F5**. You'll learn more in *Debugging and Logging*.
+:::
+
+### 4. Change one thing at a time
+
+Make one change, run again, and see what happened. If you change five things at once, you won't know which change mattered.
+
+### 5. Shrink the problem
+
+Remove or comment out code until you have the **smallest** program that still shows the bug. Often the cause becomes obvious, and a small example is what people need if you ask for help.
+
+### 6. Explain it, search it, or take a break
+
+Describe your code line by line to someone, or to a rubber duck (**rubber duck debugging**). *"And here `total` is… oh, it's a string"* finds many bugs. Still stuck? Search the error's last line, or take a ten-minute break.
+
+## Try it
+
+This program has **three** bugs: one syntax error, one runtime error, and one logic error. Fix them one at a time, and run after each fix. It should print `Area: 12.0` and `Perimeter: 14.0`.
+
+
+
+::: details Hints
+1. `SyntaxError`: look for an unclosed parenthesis.
+2. `TypeError`: what type is `width`?
+3. Wrong perimeter: which operation happens first?
+:::
+
+## Common mistakes
+
+### 1. "Fixing" the error by changing the wrong thing
+
+```py
+age = "20" # was 20, changed to silence a TypeError
+print("Age: " + age)
+print("Next year:", age + 1)
+```
+
+```text
+Age: 20
+Traceback (most recent call last):
+ File "age.py", line 3, in
+ print("Next year:", age + 1)
+ ~~~~^~~
+TypeError: can only concatenate str (not "int") to str
+```
+
+Turning the number into a string fixed line 2 but moved the error to line 3. **Fix:** keep `age = 20` and convert only where you need text: `"Age: " + str(age)`. Understand *why* a change works before moving on.
+
+### 2. Printing a value that only looks right
+
+```python
+quantity = "3"
+print(quantity)
+print(f"{quantity=}")
+```
+
+```text
+3
+quantity='3'
+```
+
+A plain `print()` shows `3` for both the string `"3"` and the number `3`. **Fix:** debug with `=` (or `!r`), which puts strings in quotes.
+
+## Practice
+
+### 1. Name the error
+
+Without running, predict the **type** of error each line raises. Treat each line as its own program:
+
+```py
+print("Hello)
+print(undefined_name)
+print(int("hello"))
+print("5" + 5)
+print(10 % 0)
+print("abc"[3])
+```
+
+::: details Solution
+1. `SyntaxError`: unterminated string
+2. `NameError`
+3. `ValueError`
+4. `TypeError`
+5. `ZeroDivisionError`
+6. `IndexError`
+:::
+
+### 2. Read the traceback
+
+Answer the questions about this traceback: Which line failed? What's the error type? What's the cause?
+
+```text
+Traceback (most recent call last):
+ File "grades.py", line 7, in
+ percent = points / max_points * 100
+ ^^^^^^^^^^
+NameError: name 'max_points' is not defined. Did you mean: 'max_point'?
+```
+
+::: details Solution
+- **Line 7** of `grades.py`.
+- **`NameError`**.
+- The variable is called `max_point` (singular) somewhere earlier, but line 7 uses `max_points`. Use the same name in both places.
+:::
+
+### 3. Fix the greeting
+
+This program should print `Hello, Aziza! You are 21 next year.` Find and fix all the bugs.
+
+```py
+name = "aziza"
+age = "20"
+print(f"Hello, {name.title}! You are {age + 1} next year."
+```
+
+::: details Solution
+```python
+name = "aziza"
+age = "20"
+print(f"Hello, {name.title()}! You are {int(age) + 1} next year.")
+```
+
+1. Missing `)` at the end → `SyntaxError`.
+2. `age + 1` with a string `age` → `TypeError`.
+3. `name.title` without `()` prints ``: a logic error with no message.
+:::
+
+### 4. The silent bug
+
+This code should convert 98.6 °F to °C (the answer is 37.0) but prints something else. Use a debugging `print()` to find the problem, then fix it.
+
+```python
+fahrenheit = 98.6
+celsius = fahrenheit - 32 * 5 / 9
+print(round(celsius, 1))
+```
+
+::: details Solution
+It prints `80.8`. Printing a piece, such as `print(f"{32 * 5 / 9=}")`, shows that `32 * 5 / 9` was calculated first: `*` and `/` come before `-`.
+
+```python
+fahrenheit = 98.6
+celsius = (fahrenheit - 32) * 5 / 9
+print(round(celsius, 1))
+```
+:::
+
+### 5. Debug a receipt
+
+This program has **four** bugs of different kinds. Fix them so it prints:
+
+```text
+Items: 3
+Subtotal: 45000
+Discount: 4500.0
+To pay: 40500.0
+```
+
+```py
+item_count = "3"
+unit_price = 15000
+discount_rate = 10
+
+subtotal = item_count * unit_price
+discount = subtotal * discount_rate
+to_pay = subtotal - discont
+
+print("Items:", item_count)
+print("Subtotal:", subtotal)
+print("Discount:", discount)
+print("To pay:" to_pay)
+```
+
+::: details Solution
+```python
+item_count = 3
+unit_price = 15000
+discount_rate = 10
+
+subtotal = item_count * unit_price
+discount = subtotal * discount_rate / 100
+to_pay = subtotal - discount
+
+print("Items:", item_count)
+print("Subtotal:", subtotal)
+print("Discount:", discount)
+print("To pay:", to_pay)
+```
+
+1. Missing comma in the last `print` → `SyntaxError` (found first, before anything runs).
+2. `discont` is misspelled → `NameError`.
+3. `"3" * 15000` builds a string of 15,000 threes without complaining. The program only crashes later, at the subtraction. `item_count` should be the number `3`.
+4. `subtotal * 10` treats the rate as ×10, not 10%. Divide by 100.
+:::
+
+## Recap
+
+- Read tracebacks **from the bottom up**: error type and message first, then the file and line.
+- **Syntax errors** stop the whole file before it runs. **Runtime errors** happen when a line runs, after earlier lines have already run.
+- **Logic errors** give wrong results with no message, so know the expected answer.
+- Debugging process: read the message → reproduce it → print values (`f"{x=}"`) or step through with a debugger → change one thing at a time → shrink the problem → explain it.
+
+## Further reading
+
+- [Python Tutorial - Errors and Exceptions](https://docs.python.org/3/tutorial/errors.html)
+- [Built-in exceptions](https://docs.python.org/3/library/exceptions.html)
diff --git a/docs/lessons/03-making-decisions/01-booleans-and-comparisons.md b/docs/lessons/03-making-decisions/01-booleans-and-comparisons.md
new file mode 100644
index 0000000..69f04ba
--- /dev/null
+++ b/docs/lessons/03-making-decisions/01-booleans-and-comparisons.md
@@ -0,0 +1,470 @@
+---
+title: Booleans and Comparisons
+description: "Understand True and False, compare values with ==, !=, <, >, <=, and >=, chain comparisons, and learn which values Python treats as truthy or falsy."
+---
+
+# Booleans and Comparisons
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- The `bool` type and its two values, `True` and `False`
+- The six comparison operators, and chains like `0 <= score <= 100`
+- How strings compare, and why `"Z" < "a"`
+- Which values count as "truthy" and "falsy"
+- How to compare floats safely, and why `is` isn't `==`
+:::
+
+## Why it matters
+
+Programs make decisions: *Is the password correct? Is the cart empty? Is the user over 18?* Every decision starts with a question whose answer is **yes or no**. In Python, those answers are **booleans**. This lesson is the foundation for `if` statements in the next lesson.
+
+## True and False
+
+Python has a type with exactly two values:
+
+```python
+is_raining = True
+has_ticket = False
+
+print(is_raining)
+print(type(has_ticket))
+```
+
+```text
+True
+
+```
+
+- `True` and `False` must be written with a **capital first letter**. `true` is just an undefined name.
+- They're not strings: `True` has no quotes, and `"True"` is a string.
+- A good name for a boolean variable reads like a yes/no question: `is_valid`, `has_discount`, `can_vote`.
+
+## Comparison operators
+
+A **comparison** asks a question about two values and produces a boolean:
+
+| Operator | Question | Example | Result |
+|---|---|---|---|
+| `==` | equal? | `5 == 5` | `True` |
+| `!=` | not equal? | `5 != 3` | `True` |
+| `<` | less than? | `3 < 5` | `True` |
+| `>` | greater than? | `3 > 5` | `False` |
+| `<=` | less than or equal? | `5 <= 5` | `True` |
+| `>=` | greater than or equal? | `4 >= 5` | `False` |
+
+```python
+age = 17
+print(age >= 18)
+print(age == 17)
+print(age != 17)
+```
+
+```text
+False
+True
+False
+```
+
+You can store the result like any other value:
+
+```python
+balance = 50000
+price = 32000
+
+can_afford = balance >= price
+print(f"Can afford: {can_afford}")
+```
+
+```text
+Can afford: True
+```
+
+::: warning `=` vs `==`
+**`=` assigns** a value (`x = 5`). **`==` compares** two values (`x == 5`). Mixing them up is one of the most common beginner mistakes.
+:::
+
+## Comparing different types
+
+Numbers compare by value, even across `int` and `float`:
+
+```python
+print(3 == 3.0)
+print(2 < 2.5)
+```
+
+```text
+True
+True
+```
+
+But a number and a string are **never equal**, and they can't be ordered:
+
+```python
+print(5 == "5")
+```
+
+```text
+False
+```
+
+```py
+print(5 < "10")
+```
+
+```text
+TypeError: '<' not supported between instances of 'int' and 'str'
+```
+
+This matters with `input()`, which returns strings. `input() == 5` is **always** `False`. Convert first: `int(input()) == 5`.
+
+## Comparing strings
+
+`==` checks whether two strings are exactly the same, **including capitalization and spaces**:
+
+```python
+print("tea" == "tea")
+print("tea" == "Tea")
+print("tea" == "tea ")
+```
+
+```text
+True
+False
+False
+```
+
+To compare without caring about case or extra spaces, clean up both sides first:
+
+```python
+answer = " YES "
+print(answer.strip().lower() == "yes")
+```
+
+```text
+True
+```
+
+### Ordering strings
+
+`<` and `>` compare strings **character by character**, using each character's code number. For plain lowercase words, that's alphabetical order:
+
+```python
+print("apple" < "banana")
+print("cat" < "car") # 't' comes after 'r'
+print("app" < "apple") # a shorter prefix comes first
+```
+
+```text
+True
+False
+True
+```
+
+Two surprises:
+
+```python
+print("Z" < "a") # all uppercase letters come before lowercase
+print("10" < "9") # compares "1" with "9", not the numbers
+```
+
+```text
+True
+True
+```
+
+To compare text alphabetically regardless of case, lower both sides. To compare numbers, convert them to numbers first.
+
+## Chaining comparisons
+
+Python lets you chain comparisons the way you'd write them in math:
+
+```python
+score = 85
+print(0 <= score <= 100) # is score between 0 and 100?
+print(80 <= score < 90) # is score in the 80s?
+```
+
+```text
+True
+True
+```
+
+`0 <= score <= 100` means `0 <= score` **and** `score <= 100`. Many other languages can't do this.
+
+A chain doesn't have to be a range. Each link is its own comparison between neighbours, and the whole chain is `True` only if every link is:
+
+```python
+a = 5
+b = 5.0
+c = 5
+print(a == b == c) # a == b and b == c
+print(1 < 3 > 2) # 1 < 3 and 3 > 2
+```
+
+```text
+True
+True
+```
+
+`1 < 3 > 2` is legal but hard to read. It says nothing about how `1` compares with `2`. Keep chains for ranges and for "all equal" checks.
+
+## Truthy and falsy values
+
+Every value in Python can be treated as a boolean. The built-in `bool()` shows how:
+
+```python
+print(bool(0), bool(0.0), bool("")) # "empty" or zero values
+print(bool(42), bool(-1), bool("hi"), bool(" "))
+```
+
+```text
+False False False
+True True True True
+```
+
+- **Falsy** values act like `False`: `0`, `0.0`, `""` (empty string), `None`, and empty collections such as `[]`.
+- **Everything else** is **truthy** and acts like `True`, including `" "` (a space) and `"False"` (a non-empty string!).
+
+You'll use this in the next lesson to write checks like "if the user typed *something*".
+
+## Booleans are numbers, too
+
+`True` behaves like `1` and `False` like `0` in arithmetic. It's occasionally handy for counting:
+
+```python
+passed_math = True
+passed_physics = False
+passed_english = True
+
+print(passed_math + passed_physics + passed_english) # how many passed
+```
+
+```text
+2
+```
+
+## Comparing floats safely
+
+From *Numbers and Math*, you know floats can be slightly inexact:
+
+```python
+print(0.1 + 0.2 == 0.3)
+```
+
+```text
+False
+```
+
+Don't use `==` on floats that come out of arithmetic. (Comparing with an exact value you wrote yourself, like `x == 0.0`, is fine.) Use `math.isclose()`, which allows a tiny difference:
+
+```python
+import math
+
+print(math.isclose(0.1 + 0.2, 0.3))
+```
+
+```text
+True
+```
+
+Comparisons with `<` and `>` are usually fine. The problem is `==` and `!=`.
+
+## `is` isn't `==`
+
+You may see `x is None` in code. `is` checks whether two names refer to the **same object**, not whether the values are equal. Two strings can hold the same text and still be different objects:
+
+```python
+first = "Al"
+name = first + "i"
+other = "Ali"
+
+print(name == other) # same text?
+print(name is other) # same object?
+
+result = None
+print(result is None)
+```
+
+```text
+True
+False
+True
+```
+
+`first + "i"` built a new string, so `name` and `other` are equal but not the same object. Whether two equal strings or numbers happen to share one object is up to Python, so `is` on them sometimes seems to work and sometimes doesn't.
+
+`None` is Python's "no value here" value, and there is only ever one `None` object. That makes `is None` the one place beginners should use `is`. For everything else, use `==`. The opposite forms are `is not` and `!=`.
+
+## Try it
+
+Change the values and predict each result before running.
+
+
+
+## Common mistakes
+
+### 1. Using `=` instead of `==`
+
+```py
+print(age = 18)
+```
+
+```text
+TypeError: print() got an unexpected keyword argument 'age'
+```
+
+Inside `print()`, `age = 18` looks like a keyword argument, like `sep=`. **Fix:** `print(age == 18)`.
+
+### 2. Comparing input to a number
+
+```python
+answer = "7" # what input() would return
+print(answer == 7) # a string is never equal to a number
+print(int(answer) == 7)
+```
+
+```text
+False
+True
+```
+
+### 3. Lowercase `true`
+
+```py
+is_open = true
+```
+
+```text
+NameError: name 'true' is not defined. Did you mean: 'True'?
+```
+
+### 4. Using `is` to compare with a value
+
+```py
+name = input("Name: ") # the user types Ali
+if name is "Ali":
+ print("Salom, Ali!")
+```
+
+```text
+SyntaxWarning: "is" with 'str' literal. Did you mean "=="?
+Name: Ali
+```
+
+Python warns before the program even starts, and then nothing is printed: the text you typed is a new string object, not the `"Ali"` in the code. **Fix:** `if name == "Ali":`.
+
+## Practice
+
+### 1. Predict
+
+Predict each result, then run to check.
+
+```python
+print(10 == 10.0)
+print("10" == 10)
+print(7 != 8)
+print("abc" < "abd")
+print(3 <= 3 < 4)
+```
+
+::: details Solution
+```text
+True
+False
+True
+True
+True
+```
+
+`"abc" < "abd"` compares the third characters, and `c` comes before `d`.
+:::
+
+### 2. Voting age
+
+Given `age = 19`, create a variable `can_vote` that is `True` if the age is 18 or more, and print it.
+
+::: details Solution
+```python
+age = 19
+can_vote = age >= 18
+print(can_vote)
+```
+:::
+
+### 3. Same word?
+
+Print `True` if `word1 = " Toshkent"` and `word2 = "TOSHKENT "` are the same word, ignoring case and surrounding spaces.
+
+::: details Solution
+```python
+word1 = " Toshkent"
+word2 = "TOSHKENT "
+print(word1.strip().lower() == word2.strip().lower())
+```
+:::
+
+### 4. Truthy or falsy?
+
+For each value, decide whether `bool()` gives `True` or `False`: `0`, `"0"`, `""`, `" "`, `0.0`, `-0.5`, `"False"`.
+
+::: details Solution
+| Value | `bool()` |
+|---|---|
+| `0` | `False` |
+| `"0"` | `True`: a non-empty string |
+| `""` | `False` |
+| `" "` | `True`: a space is a character |
+| `0.0` | `False` |
+| `-0.5` | `True`: non-zero |
+| `"False"` | `True`: a non-empty string |
+
+Check it:
+
+```python
+print(bool(0), bool("0"), bool(""), bool(" "))
+print(bool(0.0), bool(-0.5), bool("False"))
+```
+
+```text
+False True False True
+False True True
+```
+:::
+
+### 5. Valid time
+
+A time is given as text: `time_text = "23:59"`. Split it into hours and minutes, convert them to numbers, and print `True` if it's a valid 24-hour time (hours 0-23, minutes 0-59). Test with `"23:59"` (True), `"24:00"` (False), and `"07:60"` (False).
+
+::: details Solution
+```python
+time_text = "23:59"
+
+parts = time_text.split(":")
+hours = int(parts[0])
+minutes = int(parts[1])
+
+hours_ok = 0 <= hours <= 23
+minutes_ok = 0 <= minutes <= 59
+
+print(hours_ok and minutes_ok)
+```
+
+`and` combines two booleans into one. It's the topic of the *Logical Operators* lesson. Without it, you could print `hours_ok` and `minutes_ok` separately and check that both are `True`.
+:::
+
+## Recap
+
+- `bool` has two values, `True` and `False`, with capital letters and no quotes.
+- Comparisons `== != < > <= >=` produce booleans. `=` assigns and `==` compares.
+- String comparison is exact and case-sensitive, so `"Z" < "a"`. A number never equals a string: convert `input()` first.
+- Chains like `0 <= x <= 100` test each pair of neighbours.
+- Falsy values are `0`, `0.0`, `""`, `None`, and empty collections. Everything else is truthy.
+- Compare floats from arithmetic with `math.isclose()`. Use `is` only for `None`.
+
+## Further reading
+
+- [Comparisons](https://docs.python.org/3/library/stdtypes.html#comparisons)
+- [Truth value testing](https://docs.python.org/3/library/stdtypes.html#truth-value-testing)
+- [`math.isclose()`](https://docs.python.org/3/library/math.html#math.isclose)
+- [Identity comparisons (`is`)](https://docs.python.org/3/reference/expressions.html#identity-comparisons)
diff --git a/docs/lessons/03-making-decisions/02-if-elif-else.md b/docs/lessons/03-making-decisions/02-if-elif-else.md
new file mode 100644
index 0000000..dc3c5df
--- /dev/null
+++ b/docs/lessons/03-making-decisions/02-if-elif-else.md
@@ -0,0 +1,441 @@
+---
+title: if, elif, and else
+description: "Make your programs choose what to do with if, elif, and else: blocks and indentation, choosing between many options, nesting, and one-line conditional expressions."
+---
+
+# if, elif, and else
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- How to run code only when a condition is true with `if`
+- How to handle the other case with `else`
+- How to choose between many options with `elif`
+- Why the **order** of conditions matters
+- How to nest decisions, and how to write a short conditional expression
+:::
+
+## Why it matters
+
+Until now, your programs ran every line, top to bottom, every time. Real programs **react**: show an error when a password is wrong, give a discount to members, print "1 item" instead of "1 items". The `if` statement is how a program chooses what to do.
+
+## `if`: run code only when a condition is true
+
+```python
+temperature = 34
+
+if temperature > 30:
+ print("It's hot today.")
+ print("Remember to drink water.")
+
+print("Have a good day!")
+```
+
+```text
+It's hot today.
+Remember to drink water.
+Have a good day!
+```
+
+Change `temperature` to `20` and the two indented lines are **skipped**:
+
+```text
+Have a good day!
+```
+
+The structure:
+
+```text
+if condition:
+ code that runs only when the condition is True
+```
+
+- The line starts with `if`, then a condition, then a **colon** `:`.
+- The code that belongs to the `if` is **indented** (4 spaces). This indented group of lines is called a **block**.
+- The block ends when the indentation goes back. `print("Have a good day!")` isn't indented, so it always runs.
+
+The condition can be anything that is truthy or falsy (see *Booleans and Comparisons*): a comparison, a boolean variable, or any value.
+
+## `else`: otherwise…
+
+`else` gives code to run when the condition is **false**. Exactly one of the two blocks runs:
+
+```python
+age = 15
+
+if age >= 18:
+ print("You can vote.")
+else:
+ years_left = 18 - age
+ print(f"You can vote in {years_left} years.")
+```
+
+```text
+You can vote in 3 years.
+```
+
+`else` has no condition. It catches everything the `if` didn't.
+
+## `elif`: choosing between many options
+
+`elif` is short for "else if". It lets you check several conditions in order:
+
+```python
+score = 76
+
+if score >= 90:
+ grade = "A"
+elif score >= 80:
+ grade = "B"
+elif score >= 70:
+ grade = "C"
+elif score >= 60:
+ grade = "D"
+else:
+ grade = "F"
+
+print(f"Score {score} → grade {grade}")
+```
+
+```text
+Score 76 → grade C
+```
+
+How Python runs this:
+
+1. Check each condition **from top to bottom**.
+2. Run the block of the **first** condition that's true.
+3. **Skip all the rest**, even if later conditions are also true.
+4. If none are true, run `else` (if there is one).
+
+For `score = 76`: `76 >= 90` is False, `76 >= 80` is False, `76 >= 70` is True, so the grade is `"C"` and Python stops checking.
+
+You can have any number of `elif` blocks, and `else` is optional.
+
+### Order matters
+
+Because only the **first** match runs, put the most specific conditions first. This version has a bug:
+
+```python
+score = 95
+
+if score >= 60:
+ grade = "D"
+elif score >= 90:
+ grade = "A" # never reached: every score >= 90 is also >= 60
+else:
+ grade = "F"
+
+print(grade)
+```
+
+```text
+D
+```
+
+`95 >= 60` is true, so the first block runs and nothing else is checked.
+
+### `elif` vs separate `if` statements
+
+Separate `if` statements are **all** checked independently. An `elif` chain picks **only one** branch:
+
+```python
+points = 95
+
+# separate ifs: several can run
+if points > 50:
+ print("More than 50")
+if points > 90:
+ print("More than 90")
+
+# one chain: only the first match runs
+if points > 90:
+ print("Excellent")
+elif points > 50:
+ print("Good")
+```
+
+```text
+More than 50
+More than 90
+Excellent
+```
+
+Use an `if`/`elif`/`else` chain when the options **exclude each other** (one grade, one ticket price). Use separate `if` statements for **independent** checks.
+
+## Nested decisions
+
+A block can contain another `if`. Each level adds another 4 spaces of indentation:
+
+```python
+has_ticket = True
+age = 12
+
+if has_ticket:
+ if age < 14:
+ print("Welcome! Please sit with an adult.")
+ else:
+ print("Welcome! Enjoy the show.")
+else:
+ print("Please buy a ticket first.")
+```
+
+```text
+Welcome! Please sit with an adult.
+```
+
+Nesting is sometimes the clearest option, but deep nesting gets hard to read. Often you can flatten it with `elif` or with `and`/`or`, from the next lesson.
+
+## Checking for empty input
+
+Because empty strings are falsy, you can check whether the user typed anything:
+
+```python
+name = "" # imagine: name = input("Name: ").strip()
+
+if name:
+ print(f"Hello, {name}!")
+else:
+ print("You didn't enter a name.")
+```
+
+```text
+You didn't enter a name.
+```
+
+`if name:` reads as "if name is not empty".
+
+## Doing nothing: `pass`
+
+A block can't be empty. If you need a placeholder, write `pass`, which does nothing:
+
+```python
+stock = 10
+
+if stock > 0:
+ pass # TODO: handle in-stock items later
+else:
+ print("Out of stock")
+```
+
+## Conditional expressions (one-line if)
+
+When you just need to pick **one of two values**, there's a compact form:
+
+```text
+value_if_true if condition else value_if_false
+```
+
+```python
+count = 1
+word = "item" if count == 1 else "items"
+print(f"{count} {word}")
+
+temperature = -3
+state = "ice" if temperature <= 0 else "water"
+print(state)
+```
+
+```text
+1 item
+ice
+```
+
+Use this only for short, simple choices. For anything longer, a regular `if`/`else` is easier to read.
+
+## Try it
+
+Enter a number into **Values for input()**, then run the program. Try `0`, `-5`, `7`, and `12`.
+
+
+
+## Common mistakes
+
+### 1. Missing colon
+
+```py
+if age >= 18
+ print("Adult")
+```
+
+```text
+SyntaxError: expected ':'
+```
+
+### 2. Using `=` in a condition
+
+```py
+if age = 18:
+ print("Just turned 18")
+```
+
+```text
+SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
+```
+
+**Fix:** `if age == 18:`. The `:=` in the hint is the "walrus" operator, which assigns inside an expression. It's an advanced tool you don't need yet.
+
+### 3. Wrong indentation
+
+```py
+if age >= 18:
+print("Adult")
+```
+
+```text
+IndentationError: expected an indented block after 'if' statement on line 1
+```
+
+Also watch for the opposite bug: forgetting to indent a line that belongs in the block, so it always runs.
+
+```python
+balance = 100
+price = 500
+
+if balance < price:
+ print("Not enough money.")
+print("Purchase complete!") # meant to be in an else, but runs every time
+```
+
+```text
+Not enough money.
+Purchase complete!
+```
+
+### 4. Comparing input without converting
+
+```python
+guess = "7" # from input()
+if guess == 7:
+ print("Correct!")
+print("Done")
+```
+
+```text
+Done
+```
+
+`"Correct!"` never prints, because a string is never equal to a number. **Fix:** `int(guess) == 7`.
+
+## Practice
+
+### 1. Even or odd
+
+Given `number = 17`, print `17 is odd` or `17 is even` using `if`/`else`.
+
+::: details Solution
+```python
+number = 17
+
+if number % 2 == 0:
+ print(f"{number} is even")
+else:
+ print(f"{number} is odd")
+```
+:::
+
+### 2. The bigger number
+
+Given two numbers `a` and `b`, print the bigger one, or `They are equal` if they're the same. (Don't use `max()`.)
+
+::: details Solution
+```python
+a = 12
+b = 30
+
+if a > b:
+ print(a)
+elif b > a:
+ print(b)
+else:
+ print("They are equal")
+```
+:::
+
+### 3. Ticket price
+
+A cinema's prices are:
+
+- under 5: free
+- 5 to 17: 25,000 som
+- 18 to 64: 40,000 som
+- 65 and over: 20,000 som
+
+Given `age`, print the price. Test with 3, 5, 17, 18, 64, and 65.
+
+::: details Solution
+```python
+age = 17
+
+if age < 5:
+ price = 0
+elif age < 18:
+ price = 25000
+elif age < 65:
+ price = 40000
+else:
+ price = 20000
+
+if price == 0:
+ print("Free")
+else:
+ print(f"{price:,} som")
+```
+
+Because the conditions run in order, `elif age < 18` already knows `age >= 5`, so you don't need to check both ends.
+:::
+
+### 4. Singular or plural
+
+Given `minutes`, print `1 minute`, `0 minutes`, or `25 minutes`, using a **conditional expression**.
+
+::: details Solution
+```python
+minutes = 1
+unit = "minute" if minutes == 1 else "minutes"
+print(f"{minutes} {unit}")
+```
+:::
+
+### 5. Simple calculator
+
+Read two numbers and an operator (`+`, `-`, `*`, or `/`) with `input()`. Print the result. Handle two problems with clear messages: dividing by zero, and an unknown operator.
+
+::: details Solution
+```python
+a = float(input("First number: "))
+operator = input("Operator (+ - * /): ").strip()
+b = float(input("Second number: "))
+
+if operator == "+":
+ print(f"{a} + {b} = {a + b}")
+elif operator == "-":
+ print(f"{a} - {b} = {a - b}")
+elif operator == "*":
+ print(f"{a} * {b} = {a * b}")
+elif operator == "/":
+ if b == 0:
+ print("Error: can't divide by zero.")
+ else:
+ print(f"{a} / {b} = {a / b}")
+else:
+ print(f"Unknown operator: {operator}")
+```
+
+The division check is **nested** inside the `/` branch. In *The match Statement* lesson you'll see another way to write this kind of menu.
+:::
+
+## Recap
+
+- `if condition:` runs its indented **block** only when the condition is truthy.
+- `else:` runs when no earlier condition matched.
+- `elif condition:` adds more options. Python runs **only the first** true branch, so order matters.
+- Use one `if`/`elif`/`else` chain for exclusive choices and separate `if`s for independent checks.
+- `if text:` checks for non-empty text. `pass` is an empty placeholder.
+- `a if condition else b` picks one of two values in a single expression.
+
+## Further reading
+
+- [Python Tutorial - `if` statements](https://docs.python.org/3/tutorial/controlflow.html#if-statements)
+- [The `if` statement](https://docs.python.org/3/reference/compound_stmts.html#the-if-statement)
+- [Conditional expressions](https://docs.python.org/3/reference/expressions.html#conditional-expressions)
diff --git a/docs/lessons/03-making-decisions/03-logical-operators.md b/docs/lessons/03-making-decisions/03-logical-operators.md
new file mode 100644
index 0000000..ec59663
--- /dev/null
+++ b/docs/lessons/03-making-decisions/03-logical-operators.md
@@ -0,0 +1,459 @@
+---
+title: Logical Operators
+description: "Combine conditions with and, or, and not: truth tables, precedence, short-circuit evaluation, common traps, and simplifying complex conditions."
+---
+
+# Logical Operators
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- How to combine conditions with `and` and `or`
+- How to flip a condition with `not`
+- The order in which `not`, `and`, and `or` are evaluated
+- **Short-circuit** evaluation, and why it can prevent errors
+- How `in` and `not in` test "is it one of these?", and how they avoid the classic `x == "a" or "b"` trap
+:::
+
+## Why it matters
+
+Real decisions rarely depend on just one thing. *You can rent a car if you're at least 21 **and** have a license. The shop is closed on Saturday **or** Sunday. Show the login form if the user is **not** signed in.* Logical operators let you express these conditions directly, instead of nesting `if` inside `if`.
+
+## `and`: both must be true
+
+```python
+age = 25
+has_license = True
+
+if age >= 21 and has_license:
+ print("You can rent a car.")
+else:
+ print("Sorry, you can't rent a car.")
+```
+
+```text
+You can rent a car.
+```
+
+`a and b` is `True` only when **both** `a` and `b` are true:
+
+| `a` | `b` | `a and b` |
+|---|---|---|
+| `True` | `True` | `True` |
+| `True` | `False` | `False` |
+| `False` | `True` | `False` |
+| `False` | `False` | `False` |
+
+## `or`: at least one must be true
+
+```python
+day = "Sunday"
+
+if day == "Saturday" or day == "Sunday":
+ print("It's the weekend!")
+```
+
+```text
+It's the weekend!
+```
+
+`a or b` is `True` when **at least one** of them is true:
+
+| `a` | `b` | `a or b` |
+|---|---|---|
+| `True` | `True` | `True` |
+| `True` | `False` | `True` |
+| `False` | `True` | `True` |
+| `False` | `False` | `False` |
+
+## `not`: flip it
+
+`not` turns `True` into `False` and `False` into `True`:
+
+```python
+is_logged_in = False
+
+if not is_logged_in:
+ print("Please log in.")
+```
+
+```text
+Please log in.
+```
+
+`not` reads well with truthy and falsy values: `if not email:` means "if the email is empty". For comparisons, prefer the direct operator: write `x != 5` rather than `not x == 5`, and `"a" not in text` rather than `not "a" in text`.
+
+## Combining several operators
+
+### Precedence: `not`, then `and`, then `or`
+
+Like `*` before `+` in math, Python evaluates `not` first, then `and`, then `or`. All comparisons (`==`, `<`, …) happen before any of them.
+
+```python
+is_member = False
+total = 120000
+has_coupon = True
+
+# and happens first: is_member or (total > 100000 and has_coupon)
+if is_member or total > 100000 and has_coupon:
+ print("Discount applied")
+```
+
+```text
+Discount applied
+```
+
+That's correct here, but it's easy to misread. `a or b and c` always means `a or (b and c)`. If you meant `(a or b) and c`, you must write the parentheses. **Use parentheses** whenever you mix `and` and `or`, even when they aren't required: `is_member or (total > 100000 and has_coupon)`.
+
+### Ranges: chaining vs. `and`
+
+`hour >= 9 and hour < 18` is the same as the chained `9 <= hour < 18` from *Booleans and Comparisons*. For "outside a range", use `or`:
+
+```python
+hour = 22
+if hour < 9 or hour >= 18:
+ print("The office is closed.")
+```
+
+## `in` and `not in`: is it one of these?
+
+You've used `in` with strings to look for a piece of text. It also checks whether a value is one of a group of values written in parentheses:
+
+```python
+print("kent" in "Tashkent")
+print("K" in "Tashkent") # case matters
+
+city = "Samarkand"
+print(city in ("Tashkent", "Samarkand", "Bukhara"))
+print(city not in ("Tashkent", "Bukhara"))
+```
+
+```text
+True
+False
+True
+True
+```
+
+`city in ("Tashkent", "Samarkand")` means the same as `city == "Tashkent" or city == "Samarkand"`, and `not in` is its opposite. `("Tashkent", "Samarkand", "Bukhara")` is a *tuple*, a fixed group of values. You'll learn about it in *Tuples and Unpacking*. For now, `x in (a, b, c)` is a handy way to say "x is one of these".
+
+## The `or` trap
+
+This looks right, but it's wrong:
+
+```python
+color = "green"
+
+if color == "red" or "blue":
+ print("Primary-ish color!") # prints for ANY color
+```
+
+```text
+Primary-ish color!
+```
+
+Python reads it as `(color == "red") or ("blue")`. The second part is just the string `"blue"`, which is **truthy**, so the whole condition is always true.
+
+**Fix:** repeat the comparison on both sides, or better, use `in`:
+
+```python
+color = "green"
+
+if color == "red" or color == "blue":
+ print("Primary-ish color!")
+
+if color in ("red", "blue"): # cleaner
+ print("Primary-ish color!")
+```
+
+Neither prints for `"green"`.
+
+## Short-circuit evaluation
+
+Python stops evaluating as soon as it knows the answer:
+
+- `a and b`: if `a` is false, the result is `a`, and **`b` isn't evaluated**.
+- `a or b`: if `a` is true, the result is `a`, and **`b` isn't evaluated**.
+
+That lets you guard against errors by putting the safety check **first**:
+
+```python
+count = 0
+total = 50
+
+if count != 0 and total / count > 10:
+ print("High average")
+else:
+ print("No data or low average")
+```
+
+```text
+No data or low average
+```
+
+Because `count != 0` is `False`, Python never runs `total / count`, so there's no `ZeroDivisionError`. If you swap the two sides, the program crashes.
+
+## `and` and `or` return values, not just booleans
+
+Strictly speaking, `and` and `or` return **one of their operands**:
+
+- `a or b` returns `a` if `a` is truthy, otherwise `b`.
+- `a and b` returns `a` if `a` is falsy, otherwise `b`.
+
+This gives a neat trick for **default values**:
+
+```python
+name = "" # imagine: input("Name (optional): ").strip()
+
+display_name = name or "Guest"
+print(f"Welcome, {display_name}!")
+```
+
+```text
+Welcome, Guest!
+```
+
+If `name` is an empty string (falsy), you get `"Guest"`. Be careful with numbers, though: `0 or 10` gives `10`, even if `0` was a valid value.
+
+## Simplifying conditions
+
+A few rewrites make conditions easier to read. These two pairs are always equivalent (**De Morgan's laws**):
+
+| This | is the same as |
+|---|---|
+| `not (a and b)` | `not a or not b` |
+| `not (a or b)` | `not a and not b` |
+
+```python
+is_weekend = False
+is_holiday = False
+
+# Bad: hard to read
+if not (is_weekend or is_holiday):
+ print("Workday")
+
+# Good: same logic, reads naturally
+if not is_weekend and not is_holiday:
+ print("Workday")
+```
+
+Also, don't compare booleans to `True`. Write `if is_valid:` rather than `if is_valid == True:`, and `if not is_valid:` rather than `if is_valid == False:`.
+
+Naming parts of a long condition helps too:
+
+```python
+age = 30
+income = 9_000_000
+has_debt = False
+
+is_adult = age >= 18
+earns_enough = income >= 5_000_000
+
+if is_adult and earns_enough and not has_debt:
+ print("Loan pre-approved")
+```
+
+## Try it
+
+Try different values and predict whether access is granted.
+
+
+
+## Common mistakes
+
+### 1. `x == a or b`
+
+```python
+answer = "no"
+
+if answer == "yes" or "y":
+ print("You agreed!")
+```
+
+```text
+You agreed!
+```
+
+The `"y"` on its own is truthy, so the condition is always true. **Fix:** `if answer in ("yes", "y"):`.
+
+### 2. `and` when you mean `or`
+
+```python
+day = "Saturday"
+
+if day == "Saturday" and day == "Sunday": # can never be both!
+ print("Weekend")
+else:
+ print("Workday")
+```
+
+```text
+Workday
+```
+
+A variable can't equal two different values at once. **Fix:** `or`.
+
+### 3. Guard on the wrong side
+
+```py
+count = 0
+total = 50
+
+if total / count > 10 and count != 0:
+ print("High average")
+```
+
+```text
+ZeroDivisionError: division by zero
+```
+
+The division runs first, before the check has a chance to stop it. **Fix:** `if count != 0 and total / count > 10:`.
+
+### 4. Using `&&`, `||`, or `!`
+
+```py
+age = 20
+has_ticket = True
+
+if age >= 18 && has_ticket:
+ print("Welcome")
+```
+
+```text
+ if age >= 18 && has_ticket:
+ ^
+SyntaxError: invalid syntax
+```
+
+Other languages use these symbols. In Python, they're words: `and`, `or`, `not`. (`!` doesn't exist on its own, although `!=` does.)
+
+## Practice
+
+### 1. Truth table check
+
+Predict each result:
+
+```python
+print(True and not False)
+print(False or not True)
+print(not (3 > 2 and 2 > 1))
+print(5 > 3 or 1 / 0 > 0)
+```
+
+::: details Solution
+```text
+True
+False
+False
+True
+```
+
+The last line doesn't crash: `5 > 3` is `True`, so `or` never evaluates `1 / 0`.
+:::
+
+### 2. Free museum entry
+
+Entry to a museum is free for children under 7 and visitors 65 or older. Students also get in free, but not at the weekend. Given `age`, `is_student`, and `is_weekend`, print `Free entry` or `Please buy a ticket`. Test with a 20-year-old student on a weekday (free) and at the weekend (ticket), and a 70-year-old at the weekend (free).
+
+::: details Solution
+```python
+age = 20
+is_student = True
+is_weekend = False
+
+is_free = age < 7 or age >= 65 or (is_student and not is_weekend)
+
+if is_free:
+ print("Free entry")
+else:
+ print("Please buy a ticket")
+```
+
+The parentheses aren't required (`and` runs before `or`), but they show which parts belong together.
+:::
+
+### 3. Leap year
+
+A year is a **leap year** if it's divisible by 4, **except** years divisible by 100, which are only leap years if they're also divisible by 400. Given `year`, print whether it's a leap year. Test with 2024 (yes), 1900 (no), 2000 (yes), and 2026 (no).
+
+::: details Solution
+```python
+year = 1900
+
+is_leap = (year % 4 == 0 and year % 100 != 0) or year % 400 == 0
+
+if is_leap:
+ print(f"{year} is a leap year")
+else:
+ print(f"{year} is not a leap year")
+```
+:::
+
+### 4. Fix the bug
+
+This program should print `Valid answer` only for `"y"`, `"yes"`, `"n"`, or `"no"`, in any capitalization. Right now it prints `Valid answer` for everything. Fix it.
+
+```python
+answer = "maybe"
+
+if answer.lower() == "y" or "yes" or "n" or "no":
+ print("Valid answer")
+else:
+ print("Please answer yes or no")
+```
+
+::: details Solution
+```python
+answer = "maybe"
+
+if answer.lower() in ("y", "yes", "n", "no"):
+ print("Valid answer")
+else:
+ print("Please answer yes or no")
+```
+:::
+
+### 5. Password rules
+
+A password is valid if **all** of these are true:
+
+- it's at least 8 characters long,
+- it isn't all letters (it contains at least one non-letter),
+- it isn't all digits,
+- it doesn't contain the word `"password"` in any capitalization.
+
+Given `password`, print `Strong` or a message explaining the **first** rule it breaks. Test with `"abc"`, `"abcdefgh"`, `"12345678"`, `"myPassword1"`, and `"tea4two!"`.
+
+::: details Solution
+```python
+password = "tea4two!"
+
+if len(password) < 8:
+ print("Too short: use at least 8 characters.")
+elif password.isalpha():
+ print("Add at least one number or symbol.")
+elif password.isdigit():
+ print("Don't use only numbers.")
+elif "password" in password.lower():
+ print("Don't use the word 'password'.")
+else:
+ print("Strong")
+```
+
+The `elif` chain stops at the first rule that fails, so each message matches the first problem.
+:::
+
+## Recap
+
+- `and` needs both sides to be true, `or` needs at least one, and `not` flips a value.
+- Precedence is `not` → `and` → `or`. Use parentheses when mixing them.
+- `x in ("a", "b")` asks "is it one of these?". `x == "a" or "b"` is always true.
+- **Short-circuiting:** `and` stops at the first falsy value and `or` at the first truthy one, so put safety checks first.
+- `value or default` gives a fallback for empty values.
+- Simplify conditions with named booleans, De Morgan's laws, and `if flag:` instead of `if flag == True:`.
+
+## Further reading
+
+- [Boolean operations](https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not)
+- [Operator precedence](https://docs.python.org/3/reference/expressions.html#operator-precedence)
+- [Membership tests (`in`, `not in`)](https://docs.python.org/3/reference/expressions.html#membership-test-operations)
diff --git a/docs/lessons/03-making-decisions/04-match-statement.md b/docs/lessons/03-making-decisions/04-match-statement.md
new file mode 100644
index 0000000..0243a66
--- /dev/null
+++ b/docs/lessons/03-making-decisions/04-match-statement.md
@@ -0,0 +1,432 @@
+---
+title: The match Statement
+description: "Use match and case to compare a value against patterns: literal values, several options with |, the _ wildcard, capturing values, guards, and matching split commands."
+---
+
+# The match Statement
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- How `match` and `case` choose between options, and when a plain `if`/`elif` is better
+- How to match several values in one case with `|`
+- How to handle "anything else" with `_`
+- How to capture parts of a value into variables
+- How to add extra conditions with **guards**
+:::
+
+## Why it matters
+
+Many programs check one value against a list of possibilities: a menu choice, a command, a day of the week, an HTTP status code. You can do this with a long `if`/`elif` chain, but Python 3.10 added `match`, which is often clearer. It can also look **inside** values, which `if` statements can't do as neatly.
+
+::: info Version note
+`match` requires **Python 3.10 or newer**. On older versions, it's a `SyntaxError`.
+:::
+
+## A first example
+
+```python
+command = "stop"
+
+match command:
+ case "start":
+ print("Starting the engine...")
+ case "stop":
+ print("Stopping.")
+ case "pause":
+ print("Paused.")
+ case _:
+ print(f"Unknown command: {command}")
+```
+
+```text
+Stopping.
+```
+
+How it works:
+
+1. Python evaluates the value after `match` (here `command`).
+2. It tries each `case` **from top to bottom**.
+3. It runs the block of the **first** pattern that matches, and skips the rest.
+4. `case _:` matches **anything**, so it's the "otherwise" branch, like `else`.
+
+The same logic with `if`/`elif`:
+
+```python
+command = "stop"
+
+if command == "start":
+ print("Starting the engine...")
+elif command == "stop":
+ print("Stopping.")
+elif command == "pause":
+ print("Paused.")
+else:
+ print(f"Unknown command: {command}")
+```
+
+For simple value checks, the two are equally good. `match` avoids repeating `command ==` on every line.
+
+::: warning No `_`, no fallback
+If no case matches and there's no `case _:`, **nothing happens**: no error, no output. Add `case _:` whenever an unexpected value is possible.
+:::
+
+## Several values in one case: `|`
+
+`|` means "or" inside a pattern:
+
+```python
+day = "Sunday"
+
+match day:
+ case "Saturday" | "Sunday":
+ print("Weekend!")
+ case "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday":
+ print("Workday.")
+ case _:
+ print("That's not a day.")
+```
+
+```text
+Weekend!
+```
+
+Numbers work too:
+
+```python
+status = 404
+
+match status:
+ case 200 | 201:
+ print("Success")
+ case 301 | 302:
+ print("Redirect")
+ case 404:
+ print("Not found")
+ case 500:
+ print("Server error")
+ case _:
+ print(f"Other status: {status}")
+```
+
+```text
+Not found
+```
+
+## Capturing a value
+
+A plain **name** in a pattern doesn't compare against a variable. It **captures** the value into that name. This is useful in the final case:
+
+```python
+choice = "7"
+
+match choice:
+ case "1":
+ print("New game")
+ case "2":
+ print("Load game")
+ case other:
+ print(f"'{other}' is not a menu option")
+```
+
+```text
+'7' is not a menu option
+```
+
+`case other:` matches anything, like `_`, but also stores the value in `other`. Use `_` when you don't need the value.
+
+## Guards: extra conditions with `if`
+
+Add `if condition` after a pattern. The case matches only if the pattern matches **and** the condition is true:
+
+```python
+temperature = -4
+
+match temperature:
+ case 0:
+ print("Exactly freezing")
+ case t if t < 0:
+ print(f"{t}°C: below freezing, watch for ice")
+ case t if t > 35:
+ print(f"{t}°C: extreme heat")
+ case t:
+ print(f"{t}°C: normal")
+```
+
+```text
+-4°C: below freezing, watch for ice
+```
+
+Range checks like this are often just as clear with `if`/`elif`. Guards shine when combined with the patterns below.
+
+## Matching commands with several words
+
+`match` can look **inside** a sequence of values. A common use is a text command split into words with `.split()` (which you met in *String Methods and Slicing*):
+
+```python
+line = "go north"
+
+match line.split():
+ case ["go", direction]:
+ print(f"You walk {direction}.")
+ case ["take", item]:
+ print(f"You pick up the {item}.")
+ case ["look"]:
+ print("You see a dark forest.")
+ case ["quit" | "exit"]:
+ print("Goodbye!")
+ case _:
+ print("I don't understand.")
+```
+
+```text
+You walk north.
+```
+
+- `["go", direction]` matches a list of **exactly two** words where the first is `"go"`, and captures the second word in `direction`.
+- `["look"]` matches exactly one word, `"look"`.
+- `["quit" | "exit"]` matches one word that's either `"quit"` or `"exit"`.
+
+Try changing `line` to `"take lamp"`, `"look"`, `"go"`, or `"dance wildly"`. `"go"` alone doesn't match `["go", direction]`, because two words are required.
+
+With plain `if` statements, this example would need several checks of length and content. `match` has more patterns than this lesson shows. You'll meet the square brackets properly in *Lists*, and you'll match dictionaries, objects, and names like `Color.RED` in *Dictionaries*, *Dataclasses*, and *Enums*.
+
+## `match` or `if`?
+
+| Situation | Better choice |
+|---|---|
+| One value compared against several fixed options (menu, command, code) | `match` |
+| Structured values, like split commands | `match` |
+| Ranges and comparisons (`score >= 90`) | `if`/`elif` |
+| Conditions involving different variables | `if`/`elif` |
+| Only one or two options | `if`/`else` |
+
+`match` doesn't replace `if`. It's another tool that makes certain choices easier to read.
+
+## Try it
+
+Type a command into **Values for input()**, like `go east`, `take key`, `look`, or `jump`, and run it. Then add a new command, such as `drop - `. The `case []:` pattern matches an empty line: `"".split()` has no words at all.
+
+
+
+## Common mistakes
+
+### 1. Expecting a name to compare against a variable
+
+```py
+expected = "yes"
+answer = "no"
+
+match answer:
+ case expected: # captures! doesn't compare with the variable
+ print("Matched")
+ case _:
+ print("Not matched")
+```
+
+```text
+SyntaxError: name capture 'expected' makes remaining patterns unreachable
+```
+
+A bare name **captures** any value. Here Python notices that the next case can never run and refuses to run the code.
+
+If the bare name is the **last** case, there is no error at all, which is worse:
+
+```python
+expected = "yes"
+answer = "no"
+
+match answer:
+ case "maybe":
+ print("Not sure")
+ case expected: # matches anything and overwrites expected
+ print("Matched", expected)
+
+print(expected)
+```
+
+```text
+Matched no
+no
+```
+
+The case matched `"no"`, and `expected` now holds `"no"` instead of `"yes"`. **Fix:** compare against the value directly (`case "yes":`), or use `if answer == expected:`. A dotted name such as `case Color.RED:` is different: it is compared as a value, not captured. You'll use that in *Enums*.
+
+### 2. Putting `_` first
+
+```py
+answer = "y"
+
+match answer:
+ case _:
+ print("Anything")
+ case "y":
+ print("Yes")
+```
+
+```text
+SyntaxError: wildcard makes remaining patterns unreachable
+```
+
+`case _:` matches everything, so any case after it could never run. Keep `_` **last**.
+
+### 3. Using `or` instead of `|`
+
+```py
+answer = "y"
+
+match answer:
+ case "y" or "yes":
+ print("Yes")
+```
+
+```text
+ case "y" or "yes":
+ ^^
+SyntaxError: invalid syntax
+```
+
+`or` isn't allowed inside a pattern. **Fix:** `case "y" | "yes":`.
+
+## Practice
+
+### 1. Day type
+
+Given a day number `day` (1 = Monday … 7 = Sunday), print `Workday`, `Weekend`, or `Invalid day` using `match`.
+
+::: details Solution
+```python
+day = 6
+
+match day:
+ case 1 | 2 | 3 | 4 | 5:
+ print("Workday")
+ case 6 | 7:
+ print("Weekend")
+ case _:
+ print("Invalid day")
+```
+:::
+
+### 2. Traffic light
+
+Given `light` (`"red"`, `"yellow"`, or `"green"`, in any capitalization), print `Stop`, `Get ready`, or `Go`. For anything else, print `Broken light: `, with the value exactly as given.
+
+::: details Solution
+```python
+light = "Green"
+
+match light.lower():
+ case "red":
+ print("Stop")
+ case "yellow":
+ print("Get ready")
+ case "green":
+ print("Go")
+ case _:
+ print(f"Broken light: {light}")
+```
+:::
+
+### 3. Calculator with match
+
+Rewrite the calculator from *if, elif, and else* using `match` on the operator. Use a **guard** to handle division by zero.
+
+::: details Solution
+```python
+a = 12.0
+operator = "/"
+b = 0.0
+
+match operator:
+ case "+":
+ print(a + b)
+ case "-":
+ print(a - b)
+ case "*" | "x":
+ print(a * b)
+ case "/" if b == 0:
+ print("Error: can't divide by zero.")
+ case "/":
+ print(a / b)
+ case _:
+ print(f"Unknown operator: {operator}")
+```
+
+The guarded case must come **before** the plain `"/"` case, or it would never be reached.
+:::
+
+### 4. Rock, paper, scissors
+
+Given `player` and `computer` choices, print `Draw`, `You win`, or `You lose`. Use `match` on the player's choice, with guards or nested `if`s.
+
+::: details Solution
+```python
+player = "rock"
+computer = "scissors"
+
+valid = ("rock", "paper", "scissors")
+
+if player not in valid or computer not in valid:
+ print("Invalid choice")
+elif player == computer:
+ print("Draw")
+else:
+ match player:
+ case "rock":
+ print("You win" if computer == "scissors" else "You lose")
+ case "paper":
+ print("You win" if computer == "rock" else "You lose")
+ case "scissors":
+ print("You win" if computer == "paper" else "You lose")
+```
+
+Checking both choices and the draw first keeps each case simple: by the time `match` runs, `computer` is a valid choice different from `player`.
+:::
+
+### 5. Mini command shell
+
+Process a command line with `match` on `line.split()`:
+
+- `add A B`: print the sum of two numbers
+- `greet NAME`: print `Hello, NAME!`
+- `repeat WORD N`: print the word N times, separated by spaces
+- `help`: print the list of commands
+- anything else: `Unknown command. Type help.`
+
+Test with `"add 4 5"`, `"greet Aziza"`, `"repeat hi 3"`, `"help"`, and `"add 4"`.
+
+::: details Solution
+```python
+line = "repeat hi 3"
+
+match line.split():
+ case ["add", a, b]:
+ print(float(a) + float(b))
+ case ["greet", name]:
+ print(f"Hello, {name}!")
+ case ["repeat", word, times]:
+ print(((word + " ") * int(times)).strip())
+ case ["help"]:
+ print("Commands: add A B, greet NAME, repeat WORD N, help")
+ case _:
+ print("Unknown command. Type help.")
+```
+
+`"add 4"` has only two words, so it doesn't match `["add", a, b]` and falls through to `_`. `(word + " ") * int(times)` repeats the word with a space after each copy, and `.strip()` removes the extra space at the end.
+:::
+
+## Recap
+
+- `match value:` tries each `case` from top to bottom and runs only the first match.
+- `case "a" | "b":` matches several options, and `case _:` matches anything, so put it last.
+- A bare name like `case other:` **captures** the value. It doesn't compare with a variable of that name.
+- Guards (`case x if x > 0:`) add a condition to a pattern.
+- Sequence patterns like `case ["go", direction]:` match the structure of split commands.
+- Use `match` for one value against fixed options or structures, and `if`/`elif` for ranges and mixed conditions. Requires Python 3.10+.
+
+## Further reading
+
+- [Python Tutorial - `match` statements](https://docs.python.org/3/tutorial/controlflow.html#match-statements)
+- [PEP 636 - Structural pattern matching: tutorial](https://peps.python.org/pep-0636/)
+- [The `match` statement (reference)](https://docs.python.org/3/reference/compound_stmts.html#the-match-statement)
diff --git a/docs/lessons/04-loops/01-while-loops.md b/docs/lessons/04-loops/01-while-loops.md
new file mode 100644
index 0000000..5a5c5dd
--- /dev/null
+++ b/docs/lessons/04-loops/01-while-loops.md
@@ -0,0 +1,400 @@
+---
+title: while Loops
+description: "Repeat code while a condition is true: counters, loops that wait for the right input, avoiding infinite loops, and the while True pattern."
+---
+
+# while Loops
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- How a `while` loop repeats code as long as a condition is true
+- How to count and accumulate with a loop
+- How to keep asking until the user gives a valid answer
+- What an **infinite loop** is, and how to stop one
+- The `while True` + `break` pattern
+:::
+
+## Why it matters
+
+Computers are great at doing the same thing many times without getting bored or making mistakes. A game keeps running until the player quits. An ATM keeps asking for a PIN until it's correct or you run out of attempts. A download keeps waiting until it's finished. **Loops** let your program repeat work. The `while` loop repeats as long as a condition stays true.
+
+## Your first while loop
+
+```python
+count = 1
+
+while count <= 5:
+ print(f"Count is {count}")
+ count += 1
+
+print("Done!")
+```
+
+```text
+Count is 1
+Count is 2
+Count is 3
+Count is 4
+Count is 5
+Done!
+```
+
+The structure looks like an `if`:
+
+```text
+while condition:
+ body (runs again and again while the condition is True)
+```
+
+How Python runs it:
+
+1. Check the condition. If it's `False`, skip the body and continue after the loop.
+2. If it's `True`, run the whole body.
+3. Go back to step 1.
+
+The condition is checked only at the top, once per iteration. If it becomes false halfway through the body, the rest of the body still runs.
+
+Each run through the body is called an **iteration**. Here, the condition is checked 6 times: 5 times it's `True`, and on the 6th check (`count` is `6`) it's `False`, so the loop ends.
+
+::: tip Three parts of a counting loop
+1. **Start:** `count = 1`, before the loop
+2. **Condition:** `count <= 5`, checked before every iteration
+3. **Update:** `count += 1`, inside the body, moving toward the end
+:::
+
+## Tracing a loop
+
+When a loop confuses you, trace it with a table: one row per iteration.
+
+```python
+total = 0
+number = 1
+
+while number <= 4:
+ total += number
+ number += 1
+
+print(total)
+```
+
+| Check | `number` | `number <= 4` | `total` after body |
+|---|---|---|---|
+| 1 | 1 | `True` | 1 |
+| 2 | 2 | `True` | 3 |
+| 3 | 3 | `True` | 6 |
+| 4 | 4 | `True` | 10 |
+| 5 | 5 | `False` | (loop ends) |
+
+```text
+10
+```
+
+## Loops that don't count
+
+A `while` loop is most useful when you **don't know in advance** how many times to repeat. You just know when to stop:
+
+```python
+savings = 100_000
+goal = 1_000_000
+months = 0
+
+while savings < goal:
+ savings = savings * 1.05 + 100_000 # 5% growth plus a monthly deposit
+ months += 1
+
+print(f"Goal reached after {months} months: {savings:,.0f} som")
+```
+
+```text
+Goal reached after 8 months: 1,102,656 som
+```
+
+Nobody told the loop "run 8 times". It found that out by itself.
+
+## Repeating until the input is valid
+
+A classic use: keep asking until the user types something acceptable.
+
+```python
+age = int(input("Enter your age (1-120): "))
+
+while age < 1 or age > 120:
+ print("That doesn't look right. Try again.")
+ age = int(input("Enter your age (1-120): "))
+
+print(f"Thanks! You are {age}.")
+```
+
+Notice that `input()` appears twice: once before the loop, and once inside it to get a new answer. That duplication is fixed by the `while True` pattern below.
+
+### Stopping with a special value
+
+Another pattern is a **sentinel**: a special value that means "stop".
+
+```python
+total = 0
+number = int(input("Enter a number (0 to finish): "))
+
+while number != 0:
+ total += number
+ number = int(input("Enter a number (0 to finish): "))
+
+print(f"Sum: {total}")
+```
+
+With the inputs `7`, `5`, `3`, `2`, `1`, `0`:
+
+```text
+Sum: 18
+```
+
+## Infinite loops
+
+If the condition never becomes false, the loop runs **forever**:
+
+```py
+count = 1
+while count <= 5:
+ print(count)
+ # forgot count += 1, so count is always 1
+```
+
+This prints `1` endlessly. If it happens to you:
+
+- In a **terminal**, press **Ctrl + C** to stop the program.
+- In the **editor on this site**, press **Stop**, or wait for the time limit.
+
+Before running a loop, ask yourself: **what makes the condition become false?**
+
+## `while True` with `break`
+
+Sometimes it's clearest to loop "forever" and **leave from the middle** with `break`:
+
+```python
+while True:
+ answer = input("Type 'quit' to exit: ").strip().lower()
+ if answer == "quit":
+ break
+ print(f"You typed: {answer}")
+
+print("Goodbye!")
+```
+
+With the inputs `7`, `5`, `3`, `2`, `1`, `0`, `quit`, it echoes each value, then prints `Goodbye!`.
+
+`break` immediately ends the loop, no matter what the condition says. This removes the duplicated `input()` from the validation example, and it lets you fix another problem: `int(input())` crashes if the user types `twenty`. Check the text with `.isdecimal()` first. It's `True` only when the string is not empty and every character is a digit that `int()` can convert:
+
+```python
+while True:
+ text = input("Enter your age (1-120): ").strip()
+ if text.isdecimal() and 1 <= int(text) <= 120:
+ break
+ print("Please type a whole number from 1 to 120.")
+
+age = int(text)
+print(f"Thanks! You are {age}.")
+```
+
+Typing `twenty`, then `150`, then `25`:
+
+```text
+Enter your age (1-120): twenty
+Please type a whole number from 1 to 120.
+Enter your age (1-120): 150
+Please type a whole number from 1 to 120.
+Enter your age (1-120): 25
+Thanks! You are 25.
+```
+
+Short-circuiting from *Logical Operators* makes this safe: if `text.isdecimal()` is `False`, Python never runs `int(text)`.
+
+You'll learn more about `break` (and its partner `continue`) in the *break, continue, and else* lesson.
+
+## Try it
+
+A number-guessing game with a fixed secret. Put several guesses in **Values for input()**, one per line, and run it.
+
+
+
+## Common mistakes
+
+### 1. Off-by-one conditions
+
+```python
+count = 1
+while count < 5: # meant to count to 5
+ print(count)
+ count += 1
+```
+
+```text
+1
+2
+3
+4
+```
+
+Decide whether the last value should be included: `< 5` stops at 4, `<= 5` stops at 5. Tracing the last iteration catches this.
+
+### 2. Updating in the wrong place
+
+```python
+count = 1
+while count <= 3:
+ count += 1
+ print(count) # meant to print 1, 2, 3
+```
+
+```text
+2
+3
+4
+```
+
+The order of lines inside the body matters. Usually the update comes **last**.
+
+### 3. Indenting the wrong lines
+
+```py
+count = 1
+while count <= 3:
+ print(count)
+count += 1 # not indented, so it's outside the loop
+```
+
+```text
+1
+1
+1
+... (forever, until you press Stop or Ctrl + C)
+```
+
+`count += 1` never runs, so the condition never changes. Everything that should repeat must be indented under `while`. If your program seems frozen, check the update first.
+
+### 4. Converting input without checking it
+
+```py
+age = int(input("Enter your age: ")) # the user types: twenty
+```
+
+```text
+ValueError: invalid literal for int() with base 10: 'twenty'
+```
+
+**Fix:** loop with `while True`, check `text.isdecimal()`, and only then call `int()`, as in the validation example above.
+
+## Practice
+
+### 1. Countdown
+
+Print a countdown from 10 to 1, then `Liftoff!`.
+
+::: details Solution
+```python
+n = 10
+while n >= 1:
+ print(n)
+ n -= 1
+print("Liftoff!")
+```
+:::
+
+### 2. Doubling
+
+Start with `1` and keep doubling it while it's less than 1000. Print each value.
+
+::: details Solution
+```python
+value = 1
+while value < 1000:
+ print(value)
+ value *= 2
+```
+
+The last printed value is `512`. The next double, `1024`, fails the condition.
+:::
+
+### 3. Count the digits
+
+Without converting to a string, count how many digits a positive whole number has. Use `// 10` in a loop. For `number = 2026`, print `4`.
+
+::: details Solution
+```python
+number = 2026
+digits = 0
+
+while number > 0:
+ number //= 10 # remove the last digit
+ digits += 1
+
+print(digits)
+```
+
+Watch out: this prints `0` for `number = 0`. You could handle that case separately with an `if`.
+:::
+
+### 4. PIN with limited attempts
+
+The correct PIN is `"1234"`. Ask for the PIN up to **3 times**. Print `Access granted` if it's entered correctly, or `Card blocked` after 3 wrong attempts.
+
+::: details Solution
+```python
+correct_pin = "1234"
+attempts = 0
+granted = False
+
+while attempts < 3 and not granted:
+ pin = input("PIN: ")
+ attempts += 1
+ if pin == correct_pin:
+ granted = True
+ else:
+ print("Wrong PIN")
+
+if granted:
+ print("Access granted")
+else:
+ print("Card blocked")
+```
+
+The boolean `granted` is called a **flag**. It records that something happened inside the loop.
+:::
+
+### 5. Collatz sequence
+
+Start with a positive whole number `n`. While `n` isn't `1`: if it's even, divide it by 2, otherwise set it to `3 * n + 1`. Print every value, then how many steps it took. For `n = 6`, the sequence is `6 3 10 5 16 8 4 2 1` (8 steps).
+
+::: details Solution
+```python
+n = 6
+steps = 0
+
+print(n, end=" ")
+while n != 1:
+ if n % 2 == 0:
+ n //= 2
+ else:
+ n = 3 * n + 1
+ steps += 1
+ print(n, end=" ")
+
+print()
+print(f"Steps: {steps}")
+```
+
+Mathematicians believe this always reaches 1 for every starting number, but nobody has proved it yet!
+:::
+
+## Recap
+
+- `while condition:` repeats its body as long as the condition is true. The condition is checked before each iteration.
+- A counting loop needs a **start**, a **condition**, and an **update**.
+- Use `while` when you don't know in advance how many repetitions you need: waiting for valid input, reaching a goal, or a sentinel value.
+- If the condition never becomes false, you get an **infinite loop**. Stop it with Ctrl + C.
+- `while True:` with `break` leaves a loop from the middle. Combine it with `.isdecimal()` to keep asking until the input is a valid number.
+
+## Further reading
+
+- [The `while` statement](https://docs.python.org/3/reference/compound_stmts.html#the-while-statement)
+- [Python Tutorial - First steps towards programming](https://docs.python.org/3/tutorial/introduction.html#first-steps-towards-programming)
diff --git a/docs/lessons/04-loops/02-for-loops-and-range.md b/docs/lessons/04-loops/02-for-loops-and-range.md
new file mode 100644
index 0000000..00e65df
--- /dev/null
+++ b/docs/lessons/04-loops/02-for-loops-and-range.md
@@ -0,0 +1,417 @@
+---
+title: for Loops and range()
+description: "Loop over strings, lists, and number ranges with for: range() with start, stop, and step, accumulating results, nested loops, and choosing between for and while."
+---
+
+# for Loops and range()
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- How a `for` loop visits each item in a sequence
+- How to loop over the characters of a string and the items of a list
+- How to generate numbers with `range(stop)`, `range(start, stop)`, and `range(start, stop, step)`
+- How to build up a result inside a loop
+- How nested loops work, and when to choose `for` over `while`
+:::
+
+## Why it matters
+
+Most repetition in programs is "do something **for each** thing": for each student, calculate a grade; for each line in a file, check for errors; for each day in a month, add up sales. The `for` loop is built exactly for this. It's the loop you'll use most often in Python.
+
+## Looping over a sequence
+
+```python
+for letter in "Python":
+ print(letter)
+```
+
+```text
+P
+y
+t
+h
+o
+n
+```
+
+The structure:
+
+```text
+for variable in sequence:
+ body
+```
+
+On each iteration, Python takes the **next item** from the sequence, puts it in the loop variable (`letter`), and runs the body. When there are no items left, the loop ends. There's no counter to update and no condition to get wrong.
+
+It works the same way with a list, like the ones `.split()` returns:
+
+```python
+fruits = ["apple", "banana", "cherry"]
+
+for fruit in fruits:
+ print(f"Fruit: {fruit}")
+```
+
+```text
+Fruit: apple
+Fruit: banana
+Fruit: cherry
+```
+
+(Lists get their own lesson, *Lists*. For now, a list is a sequence of values in square brackets.)
+
+Choose a loop variable name that describes **one item**: `for fruit in fruits`, `for word in words`, `for student in students`.
+
+## `range()`: looping over numbers
+
+To repeat something a certain number of times, or to loop over numbers, use `range()`.
+
+### `range(stop)`
+
+`range(5)` produces `0, 1, 2, 3, 4`: five numbers, starting at 0, **stopping before** 5.
+
+```python
+for i in range(5):
+ print(i)
+```
+
+```text
+0
+1
+2
+3
+4
+```
+
+If you just need to repeat something, the loop variable can be ignored. By convention, it's then named `_`:
+
+```python
+for _ in range(3):
+ print("Hip hip hooray!")
+```
+
+### `range(start, stop)`
+
+```python
+for day in range(1, 8):
+ print(f"Day {day}")
+```
+
+This prints `Day 1` to `Day 7`. As with slicing, the **start is included and the stop is not**.
+
+### `range(start, stop, step)`
+
+```python
+for n in range(0, 21, 5):
+ print(n, end=" ")
+print()
+
+for n in range(10, 0, -2):
+ print(n, end=" ")
+print()
+```
+
+```text
+0 5 10 15 20
+10 8 6 4 2
+```
+
+A negative step counts down. The stop is still excluded, so `range(10, 0, -2)` never reaches `0`.
+
+| Call | Numbers |
+|---|---|
+| `range(4)` | `0 1 2 3` |
+| `range(2, 6)` | `2 3 4 5` |
+| `range(1, 10, 3)` | `1 4 7` |
+| `range(5, 0, -1)` | `5 4 3 2 1` |
+| `range(3, 3)` | *(nothing)* |
+
+::: info range is lazy
+`range(1_000_000)` doesn't create a million numbers in memory. It produces each one when the loop asks for it. To *see* the numbers, convert it: `list(range(5))` gives `[0, 1, 2, 3, 4]`.
+:::
+
+## Building a result in a loop
+
+A very common pattern is to create a variable **before** the loop and update it **inside**:
+
+```python
+total = 0
+
+for n in range(1, 101):
+ total += n
+
+print(f"1 + 2 + ... + 100 = {total}")
+```
+
+```text
+1 + 2 + ... + 100 = 5050
+```
+
+The same idea works for counting, and for building strings:
+
+```python
+sentence = "the quick brown fox jumps over the lazy dog"
+vowel_count = 0
+consonants = ""
+
+for char in sentence:
+ if char in "aeiou":
+ vowel_count += 1
+ elif char != " ":
+ consonants += char
+
+print(f"Vowels: {vowel_count}")
+print(f"Consonants only: {consonants}")
+```
+
+```text
+Vowels: 11
+Consonants only: thqckbrwnfxjmpsvrthlzydg
+```
+
+You'll see more of these patterns in *Common Loop Patterns*.
+
+## Inside or outside the loop?
+
+Indentation decides whether a line runs **every iteration** or **once**:
+
+```python
+for n in range(1, 4):
+ print(f"Processing {n}") # inside: runs 3 times
+print("All done") # outside: runs once, after the loop
+```
+
+```text
+Processing 1
+Processing 2
+Processing 3
+All done
+```
+
+## Nested loops
+
+A loop inside a loop runs the **entire inner loop** for each iteration of the outer loop:
+
+```python
+for row in range(1, 4):
+ for col in range(1, 4):
+ print(f"{row * col:3}", end="")
+ print() # new line after each row
+```
+
+```text
+ 1 2 3
+ 2 4 6
+ 3 6 9
+```
+
+The outer loop runs 3 times, and each time the inner loop runs 3 times, so the body of the inner loop runs 3 × 3 = 9 times.
+
+Nested loops can also draw shapes. The outer loop picks the row, and the inner loop prints that many stars on it:
+
+```python
+height = 4
+for row in range(1, height + 1):
+ for star in range(row):
+ print("*", end="")
+ print()
+```
+
+```text
+*
+**
+***
+****
+```
+
+`end=""` keeps the stars on one line, and the empty `print()` ends the row. For a line of identical characters, `print("*" * row)` does the inner loop's job in one expression.
+
+## `for` or `while`?
+
+| Use `for` when… | Use `while` when… |
+|---|---|
+| you loop over the items of a sequence | you don't know how many repetitions you'll need |
+| you know how many times to repeat | you repeat until something happens (valid input, a goal reached) |
+| examples: each character, each number from 1 to 100 | examples: a game loop, retrying a password |
+
+If you can use `for`, prefer it. It's shorter, and a `for` over a `range` always ends, so you can't forget to update a counter.
+
+## Try it
+
+Change `size` to draw a bigger multiplication table, or change the format width `4`.
+
+
+
+## Common mistakes
+
+### 1. Forgetting that `stop` is excluded
+
+```python
+for n in range(1, 10): # meant 1 to 10
+ print(n, end=" ")
+```
+
+```text
+1 2 3 4 5 6 7 8 9
+```
+
+`range(1, 10)` stops **before** 10. To include 10, write `range(1, 11)`. With a variable `n`: `range(1, n + 1)`.
+
+### 2. Looping over a number
+
+```py
+for i in 5:
+ print(i)
+```
+
+```text
+TypeError: 'int' object is not iterable
+```
+
+**Fix:** `for i in range(5):`.
+
+### 3. Resetting the result inside the loop
+
+```python
+for n in range(1, 4):
+ total = 0 # reset every iteration!
+ total += n
+print(total) # meant 1 + 2 + 3
+```
+
+```text
+3
+```
+
+**Fix:** create `total = 0` **before** the loop.
+
+### 4. Counting down without a negative step
+
+```python
+for n in range(10, 0):
+ print(n)
+print("Liftoff!")
+```
+
+```text
+Liftoff!
+```
+
+No error, and no countdown either: the default step is `+1`, and you can't get from 10 to 0 by adding. **Fix:** `range(10, 0, -1)`. A step of zero is an error instead:
+
+```py
+for n in range(10, 0, 0):
+ print(n)
+```
+
+```text
+ValueError: range() arg 3 must not be zero
+```
+
+## Practice
+
+### 1. Even numbers
+
+Print all even numbers from 2 to 20 on one line, separated by spaces. Use the `step` of `range`, not `if`.
+
+::: details Solution
+```python
+for n in range(2, 21, 2):
+ print(n, end=" ")
+print()
+```
+:::
+
+### 2. Spell it out
+
+For `word = "loop"`, print each letter in uppercase with its position, like `1: L`.
+
+::: details Solution
+```python
+word = "loop"
+position = 1
+
+for letter in word:
+ print(f"{position}: {letter.upper()}")
+ position += 1
+```
+
+In *Common Loop Patterns* you'll learn `enumerate()`, which gives you the position automatically.
+:::
+
+### 3. Factorial
+
+The factorial of `n` (written `n!`) is `1 × 2 × 3 × … × n`. Calculate `10!` with a loop. The answer is `3628800`.
+
+::: details Solution
+```python
+n = 10
+result = 1
+
+for i in range(1, n + 1):
+ result *= i
+
+print(f"{n}! = {result}")
+```
+
+For a product, start at `1`, not `0`, or everything becomes zero.
+:::
+
+### 4. Pyramid
+
+Print a centered pyramid of height 4:
+
+```text
+ *
+ ***
+ *****
+*******
+```
+
+::: details Solution
+```python
+height = 4
+
+for row in range(1, height + 1):
+ spaces = " " * (height - row)
+ stars = "*" * (2 * row - 1)
+ print(spaces + stars)
+```
+
+Work out the pattern first: row 1 has 3 spaces and 1 star, row 2 has 2 spaces and 3 stars, and so on.
+:::
+
+### 5. FizzBuzz
+
+For the numbers 1 to 30: print `Fizz` for multiples of 3, `Buzz` for multiples of 5, `FizzBuzz` for multiples of both, and the number itself otherwise.
+
+::: details Solution
+```python
+for n in range(1, 31):
+ if n % 15 == 0:
+ print("FizzBuzz")
+ elif n % 3 == 0:
+ print("Fizz")
+ elif n % 5 == 0:
+ print("Buzz")
+ else:
+ print(n)
+```
+
+The `% 15` check must come **first**. Otherwise, 15 would match `% 3` and print only `Fizz`. This is the "order matters" rule from `elif` again, and it's a famous interview question.
+:::
+
+## Recap
+
+- `for item in sequence:` runs the body once for each item: characters of a string, items of a list, or numbers from `range`.
+- `range(stop)` starts at 0. `range(start, stop, step)` includes the start and excludes the stop, and a negative step counts down.
+- Create result variables **before** the loop and update them inside.
+- Indentation decides what repeats. Code after the loop runs once.
+- Nested loops run the whole inner loop for each outer iteration.
+- Prefer `for` when looping over items or a known count, and `while` when repeating until something happens.
+
+## Further reading
+
+- [Python Tutorial - `for` statements](https://docs.python.org/3/tutorial/controlflow.html#for-statements)
+- [Python Tutorial - The `range()` function](https://docs.python.org/3/tutorial/controlflow.html#the-range-function)
diff --git a/docs/lessons/04-loops/03-break-continue-else.md b/docs/lessons/04-loops/03-break-continue-else.md
new file mode 100644
index 0000000..606841b
--- /dev/null
+++ b/docs/lessons/04-loops/03-break-continue-else.md
@@ -0,0 +1,470 @@
+---
+title: break, continue, and else
+description: "Control loops precisely: stop early with break, skip an iteration with continue, run code when a loop finishes without break, and handle nested loops."
+---
+
+# break, continue, and else
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- How to stop a loop early with `break`
+- How to skip the rest of one iteration with `continue`
+- What a loop's `else` block does, and when it runs
+- How `break` behaves in nested loops
+- How to choose between `break`, a flag variable, and a loop condition
+:::
+
+## Why it matters
+
+Loops don't always need to run to the end. When you're searching for something, you can stop as soon as you've found it. When some items are invalid, you can skip them. These small tools make loops faster, shorter, and easier to read.
+
+## `break`: stop the loop now
+
+`break` ends the loop immediately. Python continues with the first line **after** the loop:
+
+```python
+for n in range(1, 100):
+ if n * n > 50:
+ print(f"First number whose square is over 50: {n}")
+ break
+ print(f"{n} squared is {n * n}")
+
+print("Loop finished")
+```
+
+```text
+1 squared is 1
+2 squared is 4
+3 squared is 9
+4 squared is 16
+5 squared is 25
+6 squared is 36
+7 squared is 49
+First number whose square is over 50: 8
+Loop finished
+```
+
+Without `break`, the loop would keep going to 99 for no reason.
+
+`break` works the same in `while` loops. It's what makes the `while True` pattern from *while Loops* possible:
+
+```python
+attempts = 0
+
+while True:
+ attempts += 1
+ pin = input("PIN: ")
+ if pin == "7":
+ print("Unlocked")
+ break
+ if attempts == 3:
+ print("Too many attempts")
+ break
+```
+
+## `continue`: skip to the next iteration
+
+`continue` skips the **rest of the current iteration** and jumps back to the top of the loop for the next item:
+
+```python
+for n in range(1, 11):
+ if n % 3 == 0:
+ continue # skip multiples of 3
+ print(n, end=" ")
+print()
+```
+
+```text
+1 2 4 5 7 8 10
+```
+
+`continue` is useful for skipping invalid or uninteresting items early, so the main code doesn't need extra indentation:
+
+```python
+entries = ["42", "", "17", "abc", "8"]
+total = 0
+
+for entry in entries:
+ if not entry.isdigit():
+ print(f"Skipping invalid entry: {entry!r}")
+ continue
+ total += int(entry)
+
+print(f"Total: {total}")
+```
+
+```text
+Skipping invalid entry: ''
+Skipping invalid entry: 'abc'
+Total: 67
+```
+
+(`{entry!r}` shows the value with quotes, so an empty string is visible as `''`.)
+
+::: warning continue in a while loop
+In a `while` loop, make sure the **update happens before `continue`**, or you'll skip it and loop forever:
+
+```py
+n = 0
+while n < 10:
+ if n % 2 == 0:
+ continue # n never changes → infinite loop
+ print(n)
+ n += 1
+```
+:::
+
+## `break` vs `continue`
+
+| Statement | Effect |
+|---|---|
+| `break` | Leave the loop completely |
+| `continue` | Skip the rest of **this** iteration, then go on with the next one |
+| `pass` | Do nothing; just a placeholder (the loop carries on normally) |
+
+## A loop's `else` block
+
+Loops can have an `else` block. It runs when the loop **finishes normally**, meaning it wasn't stopped by `break`:
+
+```python
+secret_word = "kiwi"
+guesses = ["apple", "pear", "kiwi", "plum"]
+
+for guess in guesses:
+ if guess == secret_word:
+ print(f"Found it: {guess}")
+ break
+else:
+ print("The secret word wasn't in the list.")
+```
+
+```text
+Found it: kiwi
+```
+
+Change `secret_word` to `"mango"`, and the loop runs through every guess without breaking, so the `else` runs:
+
+```text
+The secret word wasn't in the list.
+```
+
+The best way to read `for … else` is **"for … if no break"**. It's designed for searches: `break` when you find the thing, and `else` handles "not found".
+
+A classic example, checking whether a number is prime:
+
+```python
+number = 29
+
+for divisor in range(2, number):
+ if number % divisor == 0:
+ print(f"{number} is not prime (divisible by {divisor})")
+ break
+else:
+ print(f"{number} is prime")
+```
+
+```text
+29 is prime
+```
+
+This check is only right for numbers 2 and up. For `number = 1`, `range(2, 1)` is empty, the loop never breaks, and the `else` prints `1 is prime`. In a real program, handle `number < 2` with an `if` before the loop.
+
+`while` loops can have an `else` too, with the same rule: it runs when the condition becomes false, not after a `break`. Here's the PIN check from *while Loops* again, without a flag:
+
+```python
+correct_pin = "1234"
+attempts = 0
+
+while attempts < 3:
+ pin = input("PIN: ")
+ attempts += 1
+ if pin == correct_pin:
+ print("Access granted")
+ break
+ print("Wrong PIN")
+else:
+ print("Card blocked")
+```
+
+Typing `1111`, `2222`, `3333`:
+
+```text
+PIN: 1111
+Wrong PIN
+PIN: 2222
+Wrong PIN
+PIN: 3333
+Wrong PIN
+Card blocked
+```
+
+If you type `1234` at any point, `break` skips the `else`, so the card isn't blocked.
+
+### The flag alternative
+
+Many programmers find loop `else` surprising. A **flag variable** does the same job and is easy for anyone to read:
+
+```python
+number = 29
+is_prime = True
+
+for divisor in range(2, number):
+ if number % divisor == 0:
+ is_prime = False
+ break
+
+if is_prime:
+ print(f"{number} is prime")
+else:
+ print(f"{number} is not prime")
+```
+
+Both are fine. Use whichever makes your code clearer.
+
+## Nested loops: `break` leaves only one loop
+
+`break` and `continue` affect only the **innermost** loop they're in:
+
+```python
+for row in range(1, 4):
+ for col in range(1, 4):
+ if col == 2:
+ break # leaves the inner loop only
+ print(f"({row}, {col})")
+ print(f"Finished row {row}")
+```
+
+```text
+(1, 1)
+Finished row 1
+(2, 1)
+Finished row 2
+(3, 1)
+Finished row 3
+```
+
+To stop **both** loops, use a flag that the outer loop checks:
+
+```python
+target = 6
+found = False
+
+for row in range(1, 4):
+ for col in range(1, 4):
+ if row * col == target:
+ print(f"{row} x {col} = {target}")
+ found = True
+ break
+ if found:
+ break
+```
+
+```text
+2 x 3 = 6
+```
+
+In *Return Values* you'll learn a cleaner way: put the loops in a function and `return` from it.
+
+## Try it
+
+This menu loop uses `continue` for invalid choices and `break` to quit. Put choices like `1`, `9`, `2`, `q` into **Values for input()**.
+
+
+
+## Common mistakes
+
+### 1. `break` outside a loop
+
+```py
+if True:
+ break
+```
+
+```text
+SyntaxError: 'break' outside loop
+```
+
+`break` and `continue` only work inside `for` and `while`.
+
+### 2. Misreading loop `else`
+
+```python
+for letter in "abc":
+ print(letter)
+else:
+ print("The loop didn't run") # wrong idea of what else means
+```
+
+```text
+a
+b
+c
+The loop didn't run
+```
+
+The `else` block doesn't mean "if the loop didn't run". It means "if the loop **wasn't broken**", so it runs after every normal finish, and also when the loop had zero iterations.
+
+### 3. Skipping the update with `continue`
+
+```py
+n = 0
+while n < 5:
+ if n == 2:
+ continue # jumps back to the check, n stays 2
+ print(n)
+ n += 1
+```
+
+```text
+0
+1
+(then nothing: the loop spins forever until you press Stop)
+```
+
+**Fix:** in `while` loops, update the counter **before** any `continue`.
+
+### 4. Using `break` when a condition is clearer
+
+```python
+# Bad: the loop condition is hidden inside the body
+n = 1
+while True:
+ if n > 5:
+ break
+ print(n)
+ n += 1
+
+# Good: the condition says when the loop ends
+n = 1
+while n <= 5:
+ print(n)
+ n += 1
+```
+
+```text
+1
+2
+3
+4
+5
+1
+2
+3
+4
+5
+```
+
+Both print the same numbers, but the second says in its first line when the loop stops. Use `break` when the exit point is naturally in the middle, like right after reading input.
+
+## Practice
+
+### 1. First negative
+
+Loop over `numbers = [4, 8, 15, -3, 16, -42]` and print the **first** negative number, then stop.
+
+::: details Solution
+```python
+numbers = [4, 8, 15, -3, 16, -42]
+
+for n in numbers:
+ if n < 0:
+ print(f"First negative: {n}")
+ break
+```
+:::
+
+### 2. No vowels
+
+Print the letters of `"programming"` without vowels, on one line, using `continue`.
+
+::: details Solution
+```python
+for letter in "programming":
+ if letter in "aeiou":
+ continue
+ print(letter, end="")
+print()
+```
+
+```text
+prgrmmng
+```
+:::
+
+### 3. Sum until zero
+
+Read numbers with `input()` in a `while True` loop and add them up. Stop when the user enters `0`. Skip negative numbers with a message (don't add them).
+
+::: details Solution
+```python
+total = 0
+
+while True:
+ number = int(input("Number (0 to stop): "))
+ if number == 0:
+ break
+ if number < 0:
+ print("Negative numbers are ignored.")
+ continue
+ total += number
+
+print(f"Total: {total}")
+```
+:::
+
+### 4. Search with else
+
+Given `email_list = ["ali@mail.uz", "vali@mail.uz", "gani@mail.uz"]` and `wanted = "bek@mail.uz"`, print `Registered` if the email is in the list, otherwise `Not registered`. Use a `for` loop with `else` (not the `in` operator).
+
+::: details Solution
+```python
+email_list = ["ali@mail.uz", "vali@mail.uz", "gani@mail.uz"]
+wanted = "bek@mail.uz"
+
+for email in email_list:
+ if email == wanted:
+ print("Registered")
+ break
+else:
+ print("Not registered")
+```
+
+In real code, `if wanted in email_list:` is simpler. The loop version shows how searches work underneath.
+:::
+
+### 5. Primes up to 50
+
+Print all prime numbers from 2 to 50 on one line. Use a nested loop with `break` and `else`. As a speed-up, the inner loop only needs to check divisors up to the square root of the number (`divisor * divisor <= n`).
+
+::: details Solution
+```python
+for n in range(2, 51):
+ divisor = 2
+ while divisor * divisor <= n:
+ if n % divisor == 0:
+ break
+ divisor += 1
+ else:
+ print(n, end=" ")
+print()
+```
+
+```text
+2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
+```
+
+If `n` has a divisor, it must have one no bigger than its square root, so there's no need to check further.
+:::
+
+## Recap
+
+- `break` leaves the loop immediately. `continue` skips to the next iteration.
+- Loop `else` runs only if the loop **wasn't stopped by `break`**. Read it as "if no break", which suits searches.
+- A flag variable is an easy-to-read alternative to loop `else`.
+- `break` and `continue` affect only the innermost loop.
+- In `while` loops, update your variables before `continue`.
+
+## Further reading
+
+- [Python Tutorial - `break` and `continue`, and `else` on loops](https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements)
diff --git a/docs/lessons/04-loops/04-loop-patterns.md b/docs/lessons/04-loops/04-loop-patterns.md
new file mode 100644
index 0000000..209d4b1
--- /dev/null
+++ b/docs/lessons/04-loops/04-loop-patterns.md
@@ -0,0 +1,512 @@
+---
+title: Common Loop Patterns
+description: "The loop patterns programmers use every day: counting, summing, finding the largest value, searching, building strings, running totals, enumerate(), and zip()."
+---
+
+# Common Loop Patterns
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- The **counter** and **accumulator** patterns: counting, summing, and averaging
+- The **best-so-far** pattern: finding the largest or smallest item
+- The **search** pattern: is there a match, and where is it?
+- **Building** strings and **running totals** step by step
+- Looping with positions using `enumerate()`, and over two sequences at once with `zip()`
+:::
+
+## Why it matters
+
+Once you've written a few loops, you'll notice the same shapes coming up again and again. Experienced programmers don't invent each loop from scratch. They recognize the **pattern** a problem needs and fill in the details. Learn these patterns and most loop problems become quick to solve.
+
+Most examples loop over a list of test scores, written in square brackets as in *for Loops and range()*. Everything else lists can do comes in *Lists*.
+
+```python
+scores = [72, 95, 58, 88, 64, 91]
+```
+
+## 1. Counter: how many?
+
+Start at `0`, add `1` when an item matches:
+
+```python
+scores = [72, 95, 58, 88, 64, 91]
+
+passed = 0
+for score in scores:
+ if score >= 60:
+ passed += 1
+
+print(f"{passed} of {len(scores)} passed")
+```
+
+```text
+5 of 6 passed
+```
+
+## 2. Accumulator: total, product, average
+
+Start with a neutral value, and combine each item into it:
+
+```python
+scores = [72, 95, 58, 88, 64, 91]
+
+total = 0
+for score in scores:
+ total += score
+
+average = total / len(scores)
+print(f"Total: {total}, average: {average:.1f}")
+```
+
+```text
+Total: 468, average: 78.0
+```
+
+| Goal | Start with | Update |
+|---|---|---|
+| Sum | `0` | `total += x` |
+| Product | `1` | `product *= x` |
+| Build a string | `""` | `text += x` |
+| Count | `0` | `count += 1` |
+
+For simple sums, Python has a built-in: `sum(scores)`. It's still worth knowing the loop, because the pattern works for anything you can combine.
+
+## 3. Best so far: maximum and minimum
+
+Remember the best item seen so far, and replace it when you find a better one:
+
+```python
+scores = [72, 95, 58, 88, 64, 91]
+
+highest = scores[0] # start with the first item
+for score in scores:
+ if score > highest:
+ highest = score
+
+print(f"Highest: {highest}")
+```
+
+```text
+Highest: 95
+```
+
+`scores[0]` is the first item, just as `text[0]` is the first character of a string. Start with the **first item**, not `0`: if all values were negative, starting at `0` would give a wrong answer.
+
+The built-ins `max(scores)` and `min(scores)` do this for you. The loop version is needed when you want **more than the value**, for example the name of the best student. You'll write that with `zip()` below.
+
+## 4. Search: is there one?
+
+Loop until you find a match, then stop with `break`:
+
+```python
+scores = [72, 95, 58, 88, 64, 91]
+
+first_fail = None
+for score in scores:
+ if score < 60:
+ first_fail = score
+ break
+
+if first_fail is None:
+ print("Nobody failed")
+else:
+ print(f"First failing score: {first_fail}")
+```
+
+```text
+First failing score: 58
+```
+
+`None` is Python's special "no value" marker. It's a good starting value when nothing has been found yet. Check for it with `is None`, as you saw in *Booleans and Comparisons*.
+
+If you only need yes or no, a flag works just as well: start with `found = False`, and set it to `True` before the `break`.
+
+## 5. Build a string
+
+Start with `""` and add a piece on each iteration. Adding a character only when it passes a test **filters** the text:
+
+```python
+phone = "+998 (90) 123-45-67"
+
+digits = ""
+for char in phone:
+ if char.isdecimal():
+ digits += char
+
+print(digits)
+```
+
+```text
+998901234567
+```
+
+The same pattern can change characters as it goes:
+
+```python
+word = "banana"
+
+result = ""
+for letter in word:
+ if letter == "a":
+ result += "*"
+ else:
+ result += letter
+
+print(result)
+```
+
+```text
+b*n*n*
+```
+
+## 6. Running total
+
+Keep an accumulator **and** show it at every step:
+
+```python
+daily_sales = [120, 80, 150, 60]
+
+running = 0
+for day_sales in daily_sales:
+ running += day_sales
+ print(f"+{day_sales:>4} → {running:>4}")
+```
+
+```text
++ 120 → 120
++ 80 → 200
++ 150 → 350
++ 60 → 410
+```
+
+## Positions with `enumerate()`
+
+Often you need both the **item** and its **position**. Instead of managing a counter, use `enumerate()`:
+
+```python
+tasks = ["write report", "call client", "review code"]
+
+for number, task in enumerate(tasks, start=1):
+ print(f"{number}. {task}")
+```
+
+```text
+1. write report
+2. call client
+3. review code
+```
+
+`enumerate()` gives pairs of `(position, item)`, and `number, task` unpacks each pair into two variables. Without `start=1`, counting starts at `0`.
+
+Prefer `enumerate()` over `for i in range(len(tasks)):` whenever you need the item itself.
+
+### Search: where is it?
+
+Combine `enumerate()` with the search pattern, and use the loop `else` from *break, continue, and else* for "not found":
+
+```python
+scores = [72, 95, 58, 88, 64, 91]
+
+for position, score in enumerate(scores):
+ if score < 60:
+ print(f"First failing score {score} is at position {position}")
+ break
+else:
+ print("Nobody failed")
+```
+
+```text
+First failing score 58 is at position 2
+```
+
+Positions start at `0`, so `58` is at position `2`: the third item.
+
+## Two sequences at once with `zip()`
+
+`zip()` walks through several sequences **side by side**:
+
+```python
+names = ["Aziza", "Bekzod", "Dilnoza"]
+marks = [81, 94, 88]
+
+for name, mark in zip(names, marks):
+ print(f"{name:<8} {mark}")
+```
+
+```text
+Aziza 81
+Bekzod 94
+Dilnoza 88
+```
+
+With `zip()`, the best-so-far pattern can remember the name as well as the mark:
+
+```python
+names = ["Aziza", "Bekzod", "Dilnoza"]
+marks = [81, 94, 88]
+
+best_name = names[0]
+best_mark = marks[0]
+for name, mark in zip(names, marks):
+ if mark > best_mark:
+ best_name = name
+ best_mark = mark
+
+print(f"Top student: {best_name} ({best_mark})")
+```
+
+```text
+Top student: Bekzod (94)
+```
+
+## Looping backwards with `reversed()`
+
+```python
+for n in reversed(range(1, 4)):
+ print(n)
+print("Go!")
+```
+
+```text
+3
+2
+1
+Go!
+```
+
+## Choosing a pattern
+
+| The question asks… | Pattern |
+|---|---|
+| "How many…?" | Counter |
+| "What's the total / average…?" | Accumulator |
+| "Which is the largest / cheapest / longest…?" | Best so far |
+| "Is there any… / find the first…" | Search with `break` |
+| "Where is the first…?" | Search with `enumerate()` |
+| "Keep only some characters" / "Change each letter" | Build a string |
+| "Show the progress at each step" | Running total |
+
+## Try it
+
+Analyze temperatures for a week: count hot days, find the coldest day's name, and compute the average.
+
+
+
+## Common mistakes
+
+### 1. Starting max/min at 0
+
+```python
+values = [-5, -2, -9]
+
+highest = 0
+for value in values:
+ if value > highest:
+ highest = value
+
+print(f"Highest: {highest}")
+```
+
+```text
+Highest: 0
+```
+
+`0` isn't even in the list. **Fix:** start with the first item, `highest = values[0]`.
+
+### 2. Averaging an empty sequence
+
+```py
+values = []
+print(sum(values) / len(values))
+```
+
+```text
+ZeroDivisionError: division by zero
+```
+
+Check that there's data first: `if values:`. The same goes for the best-so-far pattern: `values[0]` on an empty list raises `IndexError: list index out of range`.
+
+### 3. Forgetting `break` in a search
+
+```python
+scores = [72, 95, 58, 88, 54, 91]
+
+first_fail = None
+for score in scores:
+ if score < 60:
+ first_fail = score # no break
+
+print(f"First failing score: {first_fail}")
+```
+
+```text
+First failing score: 54
+```
+
+Without `break`, the loop keeps going and later matches overwrite earlier ones, so "find the **first**" becomes "find the **last**". **Fix:** add `break` after the assignment.
+
+### 4. Using `zip()` on sequences of different lengths
+
+```python
+names = ["Aziza", "Bekzod", "Dilnoza"]
+marks = [81, 94] # one mark is missing
+
+for name, mark in zip(names, marks):
+ print(f"{name:<8} {mark}")
+```
+
+```text
+Aziza 81
+Bekzod 94
+```
+
+No error: `zip()` silently stops at the shortest sequence, and Dilnoza disappears. If the lengths should match, compare `len(names)` and `len(marks)` before the loop.
+
+## Practice
+
+### 1. Count long words
+
+Count how many words in `"Python makes repetitive tasks simple and fun"` have more than 4 letters.
+
+::: details Solution
+```python
+sentence = "Python makes repetitive tasks simple and fun"
+
+count = 0
+for word in sentence.split():
+ if len(word) > 4:
+ count += 1
+
+print(count)
+```
+
+```text
+5
+```
+:::
+
+### 2. Longest word
+
+Find the longest word in the same sentence using the best-so-far pattern.
+
+::: details Solution
+```python
+sentence = "Python makes repetitive tasks simple and fun"
+words = sentence.split()
+
+longest = words[0]
+for word in words:
+ if len(word) > len(longest):
+ longest = word
+
+print(longest)
+```
+
+```text
+repetitive
+```
+:::
+
+### 3. Numbered shopping list
+
+Given `items = ["bread", "milk", "eggs"]` and `prices = [6000, 12000, 18000]`, print a numbered list with prices, then the total. Use `zip()`, a counter, and an accumulator:
+
+```text
+1. bread 6,000
+2. milk 12,000
+3. eggs 18,000
+Total: 36,000
+```
+
+::: details Solution
+```python
+items = ["bread", "milk", "eggs"]
+prices = [6000, 12000, 18000]
+
+number = 0
+total = 0
+for item, price in zip(items, prices):
+ number += 1
+ total += price
+ print(f"{number}. {item:<6} {price:>7,}")
+
+print(f"Total: {total:,}")
+```
+:::
+
+### 4. Capitalize every other letter
+
+Turn `"python loops"` into `"PyThOn lOoPs"`: uppercase the characters at even positions and lowercase the others (count spaces as positions too).
+
+::: details Solution
+```python
+text = "python loops"
+
+result = ""
+for i, char in enumerate(text):
+ if i % 2 == 0:
+ result += char.upper()
+ else:
+ result += char.lower()
+
+print(result)
+```
+:::
+
+### 5. Stock analysis
+
+Given daily closing prices `prices = [100, 104, 101, 110, 108, 115, 112]`, print:
+
+1. the biggest one-day **increase** and which day it happened (day numbers start at 1),
+2. how many days the price went **down** compared with the day before,
+3. whether the price ever dropped **below the first day's price**.
+
+::: details Solution
+```python
+prices = [100, 104, 101, 110, 108, 115, 112]
+
+biggest_rise = 0
+rise_day = None
+down_days = 0
+
+for day in range(1, len(prices)):
+ change = prices[day] - prices[day - 1]
+ if change > biggest_rise:
+ biggest_rise = change
+ rise_day = day + 1 # human day numbers start at 1
+ if change < 0:
+ down_days += 1
+
+dropped_below_start = False
+for price in prices:
+ if price < prices[0]:
+ dropped_below_start = True
+ break
+
+print(f"Biggest rise: +{biggest_rise} on day {rise_day}")
+print(f"Down days: {down_days}")
+print(f"Dropped below start: {dropped_below_start}")
+```
+
+```text
+Biggest rise: +9 on day 4
+Down days: 3
+Dropped below start: False
+```
+
+Here, `range(1, len(prices))` is the right tool, because each step compares an item with the **previous** one. The second loop is a search with a flag.
+:::
+
+## Recap
+
+- **Counter:** start at `0`, add `1` on a match. **Accumulator:** start neutral (`0`, `1`, `""`) and combine.
+- **Best so far:** start with the first item and replace it when you find something better. `max()`/`min()` cover simple cases.
+- **Search:** loop and `break` on the first match. Use `None` or a flag for "not found yet", or a loop `else`.
+- **Build strings** with `+=`, adding only the characters you want. A **running total** prints the accumulator at each step.
+- `enumerate()` gives positions, `zip()` pairs up sequences (and stops at the shortest), and `reversed()` goes backwards.
+
+## Further reading
+
+- [Built-in functions: `enumerate()`, `zip()`, `reversed()`, `sum()`, `max()`](https://docs.python.org/3/library/functions.html)
+- [Python Tutorial - Looping techniques](https://docs.python.org/3/tutorial/datastructures.html#looping-techniques)
diff --git a/docs/lessons/04-loops/05-number-guessing-game.md b/docs/lessons/04-loops/05-number-guessing-game.md
new file mode 100644
index 0000000..21b0b17
--- /dev/null
+++ b/docs/lessons/04-loops/05-number-guessing-game.md
@@ -0,0 +1,764 @@
+---
+title: "Project: Number Guessing Game"
+description: "Build a complete number guessing game with random numbers, hints, input validation, limited attempts, difficulty levels, a play-again loop, and a best score."
+---
+
+# Project: Number Guessing Game
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- How to plan a small program before you write any code
+- How to combine `while` loops, `if`/`elif`/`else`, `match`, `break`, and `continue` in one program
+- How to validate player input with `isdecimal()` so a typo doesn't crash the game
+- How to track state across rounds: attempts, wins, and a best score
+- How to leave nested loops cleanly with a flag variable
+:::
+
+## Why it matters
+
+You now know variables, strings, input, conditions, and loops. Each lesson showed one tool at a time. A real program uses all of them together, and the new challenge is deciding **which loop goes where** and **which variables must survive between rounds**.
+
+A guessing game is a classic first project because it is small but complete: it talks to the player, reacts to mistakes, keeps score, and ends cleanly. Every interactive program you write later, from an ATM menu to a chat bot, follows the same shape.
+
+## Goal and features
+
+The computer picks a secret number. The player guesses, and the computer answers "too high" or "too low" until the player finds it or runs out of attempts. A finished session looks like this:
+
+```text
+Guess 1/7: 50
+ Too high!
+Guess 2/7: 25
+ Too low!
+Guess 3/7: abc
+ That is not a whole number. Try again.
+...
+Correct! The number was 42. You needed 7 attempts.
+New best score!
+Play again? (y/n):
+```
+
+Features:
+
+| Feature | Tools you will use |
+|---|---|
+| A random secret number | `random.randint()` |
+| "Too high" / "Too low" hints | `if` / `elif` / `else` |
+| Count attempts and limit them | `while`, a counter variable |
+| Reject bad input like `abc` or `-5` | `strip()`, `isdecimal()`, `continue` |
+| Difficulty levels (range and attempts) | `match` with or-patterns |
+| Play again, best score, and a summary | an outer `while` loop, `break` |
+| Type `quit` at any prompt | a flag variable |
+
+## Design
+
+Before writing code, draw the flow. The game has **two loops**: an outer loop for rounds and an inner loop for guesses inside one round.
+
+```text
+start: rounds_played = 0, wins = 0, best_score = None, playing = True
+ |
+ v
+OUTER LOOP (one round) - repeats while playing
+ |
+ +-- ask difficulty ------- bad answer? -> message, ask again
+ +-- set max_number, max_attempts
+ +-- pick secret, attempts = 0, won = False
+ |
+ +-- INNER LOOP (one guess) - repeats while attempts < max_attempts
+ | |
+ | +-- "quit"? -> playing = False, leave both loops
+ | +-- not a number / too big? -> message, ask again (no attempt used)
+ | +-- attempts += 1
+ | +-- too low / too high? -> hint, next guess
+ | +-- correct? -> won = True, leave inner loop
+ |
+ +-- show result, update wins and best_score
+ +-- "Play again?" ------- not y? -> playing = False
+ |
+ v
+print summary
+```
+
+The variables fall into two groups, and keeping them apart is the key design decision:
+
+| Lives for the whole session | Reset at the start of every round |
+|---|---|
+| `rounds_played`, `wins`, `best_score`, `playing` | `secret`, `attempts`, `won`, `max_number`, `max_attempts` |
+
+Session variables are created **before** the outer loop. Round variables are set **inside** it.
+
+## Step 1: Pick a secret number
+
+Python has a built-in collection of ready-made tools called the **standard library**. The `random` module can pick random numbers. You will learn about modules properly in *Modules and Imports*. For now, one line at the top of the file is enough: `import random`.
+
+```python
+import random
+
+random.seed(7)
+
+secret = random.randint(1, 100)
+print(f"Secret number: {secret}")
+
+dice = random.randint(1, 6)
+print(f"Dice roll: {dice}")
+```
+
+```text
+Secret number: 42
+Dice roll: 2
+```
+
+`random.randint(a, b)` returns a whole number from `a` to `b`, and **both ends are included**, so `randint(1, 100)` can return 1 or 100.
+
+Normally you want a different number every game. While you are building and testing, though, a changing number is annoying: you cannot repeat a bug. `random.seed(7)` makes the "random" numbers the same on every run. This lesson uses a seed so the outputs you see here are real and repeatable. Delete the `seed` line when you want to play for real.
+
+## Step 2: One guess with hints and validation
+
+`int(input())` crashes if the player types `abc`. Check the text first with `isdecimal()`, which is `True` only when a string is non-empty and every character is a decimal digit (a character `int()` can convert):
+
+```python
+print("42".isdecimal())
+print("abc".isdecimal())
+print("-5".isdecimal())
+print("4.5".isdecimal())
+print("".isdecimal())
+print(" 42".isdecimal(), " 42".strip().isdecimal())
+```
+
+```text
+True
+False
+False
+False
+False
+False True
+```
+
+Notice that `"-5"` and `"4.5"` are rejected. That is fine for this game, because the secret is never negative or a decimal. Always `strip()` first, so a stray space does not make a good answer fail.
+
+You may also meet `isdigit()`. It looks similar, but it also accepts characters like `²`, and `int("²")` raises `ValueError`. `isdecimal()` is the safe test before `int()`.
+
+Now one complete guess:
+
+```python
+secret = 42
+
+text = input("Guess a number from 1 to 100: ").strip()
+
+if not text.isdecimal():
+ print("That is not a whole number.")
+else:
+ guess = int(text)
+ if guess < 1 or guess > 100:
+ print("Please stay between 1 and 100.")
+ elif guess < secret:
+ print("Too low!")
+ elif guess > secret:
+ print("Too high!")
+ else:
+ print("Correct!")
+```
+
+Two runs, typing `abc` and then `70`:
+
+```text
+Guess a number from 1 to 100: abc
+That is not a whole number.
+Guess a number from 1 to 100: 70
+Too high!
+```
+
+The order of the checks matters. First "is it a number at all?", then "is it in range?", and only then compare it with the secret. `int(text)` is safe inside the `else`, because `isdecimal()` already said yes.
+
+## Step 3: A loop with an attempt counter and a limit
+
+One guess is not a game. Wrap it in a `while` loop that counts attempts and stops at the limit:
+
+```python
+secret = 42
+max_attempts = 5
+attempts = 0
+
+while attempts < max_attempts:
+ text = input(f"Guess {attempts + 1}/{max_attempts}: ").strip()
+ if not text.isdecimal():
+ print(" That is not a whole number. Try again.")
+ continue
+
+ guess = int(text)
+ attempts += 1
+ if guess < secret:
+ print(" Too low!")
+ elif guess > secret:
+ print(" Too high!")
+ else:
+ print(f"Correct! You needed {attempts} attempts.")
+ break
+else:
+ print(f"Out of attempts. The number was {secret}.")
+```
+
+A winning run:
+
+```text
+Guess 1/5: 50
+ Too high!
+Guess 2/5: 30
+ Too low!
+Guess 3/5: hello
+ That is not a whole number. Try again.
+Guess 3/5: 45
+ Too high!
+Guess 4/5: 42
+Correct! You needed 4 attempts.
+```
+
+And a losing run:
+
+```text
+Guess 1/5: 10
+ Too low!
+Guess 2/5: 20
+ Too low!
+Guess 3/5: 30
+ Too low!
+Guess 4/5: 40
+ Too low!
+Guess 5/5: 50
+ Too high!
+Out of attempts. The number was 42.
+```
+
+Three details to notice:
+
+- `continue` skips the rest of the loop body, so `hello` **does not use up an attempt**. The counter only grows after the input passed validation.
+- `break` leaves the loop as soon as the player wins.
+- The `else` block of the `while` loop runs only when the loop ended **without** `break`, which here means "the player ran out of attempts". You met this in *break, continue, and else*.
+
+## Step 4: Difficulty levels with `match`
+
+Each difficulty sets two values: the size of the range and the number of attempts. `match` handles this neatly, and `|` lets the player type either the number or the word:
+
+```python
+while True:
+ print("1) Easy 2) Medium 3) Hard")
+ choice = input("Choose a difficulty: ").strip().lower()
+
+ match choice:
+ case "1" | "easy":
+ max_number = 50
+ max_attempts = 10
+ case "2" | "medium":
+ max_number = 100
+ max_attempts = 7
+ case "3" | "hard":
+ max_number = 100
+ max_attempts = 5
+ case _:
+ print(" Please type 1, 2, or 3.")
+ continue
+ break
+
+print(f"Range 1-{max_number}, {max_attempts} attempts")
+```
+
+```text
+1) Easy 2) Medium 3) Hard
+Choose a difficulty: 5
+ Please type 1, 2, or 3.
+1) Easy 2) Medium 3) Hard
+Choose a difficulty: hard
+Range 1-100, 5 attempts
+```
+
+The loop runs until the player gives a valid answer. The `case _:` branch catches everything else and uses `continue` to ask again. After a valid `case`, the code reaches `break`.
+
+With 7 attempts on 1-100, a smart player always wins: guess the middle (50), then the middle of the half that is left (25 or 75), and so on. Each guess cuts the range in half, and 100 halves to 1 in 7 steps. With only 5 attempts on the same range, the player needs some luck. That is what makes "hard" hard.
+
+## Step 5: Best score and playing again
+
+The best score is the **smallest** number of attempts in a won round. Start with `None` to mean "no wins yet", the "nothing found yet" marker from *Common Loop Patterns*, and replace it when there is no best score yet or the new result is better. Here is the logic on its own, with made-up results:
+
+```python
+results = "7 4 9 3 5" # attempts used in five won rounds
+
+best_score = None # no wins yet
+for word in results.split():
+ attempts = int(word)
+ if best_score is None or attempts < best_score:
+ best_score = attempts
+ print(f"Won in {attempts} attempts. New best score!")
+ else:
+ print(f"Won in {attempts} attempts. Best is still {best_score}.")
+```
+
+```text
+Won in 7 attempts. New best score!
+Won in 4 attempts. New best score!
+Won in 9 attempts. Best is still 4.
+Won in 3 attempts. New best score!
+Won in 5 attempts. Best is still 3.
+```
+
+`best_score is None or attempts < best_score` is checked left to right. The first win always becomes the best score, because `best_score is None` is `True`. Short-circuiting also matters here: while `best_score` is `None`, Python never runs `attempts < best_score`, which would raise a `TypeError`.
+
+The play-again loop wraps a whole round. Accept `y` or `yes`, and treat anything else as "no":
+
+```python
+rounds = 0
+
+while True:
+ rounds += 1
+ print(f"--- Round {rounds} ---")
+ print("(one full game runs here)")
+
+ again = input("Play again? (y/n): ").strip().lower()
+ if again != "y" and again != "yes":
+ break
+
+print(f"Thanks for playing {rounds} rounds!")
+```
+
+```text
+--- Round 1 ---
+(one full game runs here)
+Play again? (y/n): y
+--- Round 2 ---
+(one full game runs here)
+Play again? (y/n): Y
+--- Round 3 ---
+(one full game runs here)
+Play again? (y/n): no
+Thanks for playing 3 rounds!
+```
+
+`.lower()` turns `Y` into `y`, so both work.
+
+## Step 6: Quit from anywhere
+
+The game has a loop inside a loop. `break` leaves only the **innermost** loop, so typing `quit` during a guess would just end the round and ask "Play again?". To stop everything, set a flag that the outer loop checks:
+
+```python
+playing = True
+
+while playing:
+ print("New round")
+ while True:
+ text = input("Guess: ").strip().lower()
+ if text == "quit":
+ playing = False
+ break
+ print(f" You guessed {text}")
+
+print("Bye!")
+```
+
+```text
+New round
+Guess: 50
+ You guessed 50
+Guess: 20
+ You guessed 20
+Guess: quit
+Bye!
+```
+
+`playing = False` alone does not stop the inner loop right away, and `break` alone does not stop the outer loop. Together they end the program at once. In the full game, one more `if not playing: break` right after the inner loop skips the result and the "Play again?" question.
+
+## The full program
+
+Here is everything in one file. The comments show which step each part came from. Copy it into `guessing_game.py` and run it.
+
+```python
+import random
+
+random.seed(7) # same numbers every run while testing; delete this line to play for real
+
+print("=== Number Guessing Game ===")
+print("Type quit at any prompt to stop.")
+
+rounds_played = 0
+wins = 0
+best_score = None # no wins yet
+playing = True
+
+while playing:
+ # ---------- Step 4: choose a difficulty ----------
+ print()
+ print("Difficulty: 1) Easy 1-50, 10 attempts")
+ print(" 2) Medium 1-100, 7 attempts")
+ print(" 3) Hard 1-100, 5 attempts")
+ choice = input("Choose 1, 2, or 3: ").strip().lower()
+
+ match choice:
+ case "1" | "easy":
+ max_number = 50
+ max_attempts = 10
+ case "2" | "medium":
+ max_number = 100
+ max_attempts = 7
+ case "3" | "hard":
+ max_number = 100
+ max_attempts = 5
+ case "quit" | "q":
+ break
+ case _:
+ print(" Please type 1, 2, 3, or quit.")
+ continue
+
+ # ---------- Step 1: pick a secret number ----------
+ secret = random.randint(1, max_number)
+ attempts = 0
+ won = False
+ print(f"I am thinking of a number from 1 to {max_number}.")
+ print(f"You have {max_attempts} attempts. Good luck!")
+
+ # ---------- Steps 2-3: the guessing loop ----------
+ while attempts < max_attempts:
+ text = input(f"Guess {attempts + 1}/{max_attempts}: ").strip().lower()
+
+ if text == "quit" or text == "q":
+ playing = False
+ break
+ if not text.isdecimal():
+ print(" That is not a whole number. Try again.")
+ continue
+
+ guess = int(text)
+ if guess < 1 or guess > max_number:
+ print(f" Please stay between 1 and {max_number}.")
+ continue
+
+ attempts += 1
+ if guess < secret:
+ print(" Too low!")
+ elif guess > secret:
+ print(" Too high!")
+ else:
+ won = True
+ break
+
+ if not playing:
+ break
+
+ # ---------- Step 5: results and best score ----------
+ rounds_played += 1
+ if won:
+ wins += 1
+ print(f"Correct! The number was {secret}. You needed {attempts} attempts.")
+ if best_score is None or attempts < best_score:
+ best_score = attempts
+ print("New best score!")
+ else:
+ print(f"Out of attempts. The number was {secret}.")
+
+ # ---------- Step 6: play again? ----------
+ again = input("Play again? (y/n): ").strip().lower()
+ if again != "y" and again != "yes":
+ playing = False
+
+print()
+print("=== Game over ===")
+print(f"Rounds played: {rounds_played}")
+print(f"Rounds won: {wins}")
+if best_score is not None:
+ print(f"Best score: {best_score} attempts")
+else:
+ print("Best score: no wins yet")
+```
+
+A real session. The player chooses medium, wins in 7 attempts, plays a hard round, and wins it in 5:
+
+```text
+=== Number Guessing Game ===
+Type quit at any prompt to stop.
+
+Difficulty: 1) Easy 1-50, 10 attempts
+ 2) Medium 1-100, 7 attempts
+ 3) Hard 1-100, 5 attempts
+Choose 1, 2, or 3: 2
+I am thinking of a number from 1 to 100.
+You have 7 attempts. Good luck!
+Guess 1/7: 50
+ Too high!
+Guess 2/7: 25
+ Too low!
+Guess 3/7: abc
+ That is not a whole number. Try again.
+Guess 3/7: 37
+ Too low!
+Guess 4/7: 43
+ Too high!
+Guess 5/7: 40
+ Too low!
+Guess 6/7: 41
+ Too low!
+Guess 7/7: 42
+Correct! The number was 42. You needed 7 attempts.
+New best score!
+Play again? (y/n): y
+
+Difficulty: 1) Easy 1-50, 10 attempts
+ 2) Medium 1-100, 7 attempts
+ 3) Hard 1-100, 5 attempts
+Choose 1, 2, or 3: 4
+ Please type 1, 2, 3, or quit.
+
+Difficulty: 1) Easy 1-50, 10 attempts
+ 2) Medium 1-100, 7 attempts
+ 3) Hard 1-100, 5 attempts
+Choose 1, 2, or 3: 3
+I am thinking of a number from 1 to 100.
+You have 5 attempts. Good luck!
+Guess 1/5: 150
+ Please stay between 1 and 100.
+Guess 1/5: 50
+ Too high!
+Guess 2/5: 25
+ Too high!
+Guess 3/5: 12
+ Too low!
+Guess 4/5: 18
+ Too low!
+Guess 5/5: 20
+Correct! The number was 20. You needed 5 attempts.
+New best score!
+Play again? (y/n): n
+
+=== Game over ===
+Rounds played: 2
+Rounds won: 2
+Best score: 5 attempts
+```
+
+Match the output to the rules:
+
+- `abc` and `150` were rejected, and they did not use an attempt: the counter stayed at `3/7` and `1/5`.
+- The first win set the best score to 7. The second win took only 5 attempts, so it replaced it.
+- `4` is not a difficulty, so the menu appeared again.
+- The summary counts rounds and wins that were stored **outside** the outer loop, so they survived every round.
+
+## Try it
+
+A compact version with one round on medium difficulty and no seed, so the number changes every run. Type your guesses in **Values for input()**, one per line (for example `50`, `25`, `37`). Then try adding a difficulty menu.
+
+
+
+## Common mistakes
+
+### 1. Converting input without checking it
+
+```py
+text = "abc" # what the player typed
+guess = int(text)
+```
+
+```text
+ValueError: invalid literal for int() with base 10: 'abc'
+```
+
+One typo and the whole game crashes. **Fix:** `strip()` the text, check `isdecimal()`, and `continue` when it fails. Convert with `int()` only after the check.
+
+### 2. Comparing text with a number
+
+```py
+secret = 42
+guess = input("Guess: ") # the player types 50, but guess is the string "50"
+if guess < secret:
+ print("Too low!")
+```
+
+```text
+TypeError: '<' not supported between instances of 'str' and 'int'
+```
+
+`input()` always returns a string. `"42" == 42` does not crash, but it is always `False`, so the player could never win. **Fix:** convert with `int()` (after validation) before comparing.
+
+### 3. Picking the secret inside the guessing loop
+
+```python
+import random
+
+random.seed(7)
+for text in "50 50 50".split(): # the same guess three times
+ secret = random.randint(1, 100) # Bad: a new secret before every guess
+ guess = int(text)
+ if guess < secret:
+ print(f"{guess}: Too low!")
+ elif guess > secret:
+ print(f"{guess}: Too high!")
+ else:
+ print(f"{guess}: Correct!")
+```
+
+```text
+50: Too high!
+50: Too high!
+50: Too low!
+```
+
+The same guess gets different hints, because each one refers to a new secret. **Fix:** pick the secret **once per round**, before the inner loop starts.
+
+### 4. Forgetting to reset round variables
+
+```python
+max_attempts = 3
+attempts = 0 # Bad: set once, outside the rounds loop
+
+for round_number in range(1, 3):
+ print(f"Round {round_number}")
+ while attempts < max_attempts:
+ attempts += 1
+ print(f" Guess {attempts}/{max_attempts}")
+```
+
+```text
+Round 1
+ Guess 1/3
+ Guess 2/3
+ Guess 3/3
+Round 2
+```
+
+In the second round `attempts` is still 3, so the inner loop does not run at all and the player loses without a single guess. **Fix:** set `attempts = 0` and `won = False` at the start of **every** round, inside the outer loop.
+
+## Challenges
+
+Try each one before opening the hints. Challenges 1 and 2 also have a reference solution. To make its output repeatable (and let the Check button compare yours with it), the solution uses a fixed secret and takes the guesses from a string instead of `input()`. Test your version the same way before adding it to the full game.
+
+### 1. Attempts left
+
+After each wrong guess, show how many attempts remain, for example `Too low! 4 attempts left.`, and use the word "attempt" (not "attempts") when only one is left.
+
+::: details Hints
+- `max_attempts - attempts` is the number left.
+- Pick the word with a conditional expression: `word = "attempt" if left == 1 else "attempts"`.
+- Do not print the message after the winning guess.
+:::
+
+Test it with `secret = 42`, `max_attempts = 5`, and the guesses `"50 25 40 41 42"`.
+
+::: details Solution
+```python
+secret = 42
+max_attempts = 5
+attempts = 0
+
+for text in "50 25 40 41 42".split(): # the player's guesses
+ guess = int(text)
+ attempts += 1
+ if guess == secret:
+ print(f"Correct! You needed {attempts} attempts.")
+ break
+
+ left = max_attempts - attempts
+ word = "attempt" if left == 1 else "attempts"
+ if guess < secret:
+ print(f"Too low! {left} {word} left.")
+ else:
+ print(f"Too high! {left} {word} left.")
+else:
+ print(f"Out of attempts. The number was {secret}.")
+```
+
+```text
+Too high! 4 attempts left.
+Too low! 3 attempts left.
+Too low! 2 attempts left.
+Too low! 1 attempt left.
+Correct! You needed 5 attempts.
+```
+
+In the game, replace the `for` line with the `while attempts < max_attempts:` loop and `input()`.
+:::
+
+### 2. Hot and cold
+
+Add a second hint based on distance: `(very hot)` when the guess is within 3 of the secret, `(warm)` within 10, and `(cold)` otherwise.
+
+::: details Hints
+- `abs(guess - secret)` gives the distance without worrying about the sign.
+- Check the smallest distance first: `if distance <= 3` then `elif distance <= 10`.
+- Build the message with an f-string, for example `f" Too low! ({heat})"`.
+:::
+
+Test it with `secret = 42` and the guesses `"70 35 45 42"`.
+
+::: details Solution
+```python
+secret = 42
+
+for text in "70 35 45 42".split(): # the player's guesses
+ guess = int(text)
+ if guess == secret:
+ print("Correct!")
+ break
+
+ distance = abs(guess - secret)
+ if distance <= 3:
+ heat = "very hot"
+ elif distance <= 10:
+ heat = "warm"
+ else:
+ heat = "cold"
+
+ if guess < secret:
+ print(f"{guess}: Too low! ({heat})")
+ else:
+ print(f"{guess}: Too high! ({heat})")
+```
+
+```text
+70: Too high! (cold)
+35: Too low! (warm)
+45: Too high! (very hot)
+Correct!
+```
+:::
+
+### 3. Show the remaining range
+
+Help the player by showing what is still possible: after `50 -> too high` and `25 -> too low`, print `The number is between 26 and 49.`
+
+::: details Hints
+- Keep two round variables, `low = 1` and `high = max_number`, reset every round.
+- Too low: `low = guess + 1`. Too high: `high = guess - 1`. Without the bonus below, a guess outside the range could widen it again, so only move a bound inward: change `low` only if `guess + 1 > low`, and `high` only if `guess - 1 < high`.
+- Bonus: reject guesses outside `low..high` without using an attempt, because they cannot be right.
+:::
+
+### 4. Custom difficulty and statistics
+
+Add a fourth level, `4) Custom`, where the player enters the largest number and the number of attempts (both validated). At the end, also print the average attempts per won round.
+
+::: details Hints
+- Reuse the `isdecimal()` validation pattern in a small `while True` loop for each value.
+- Reject a custom range smaller than 2 and attempts smaller than 1.
+- Keep `total_attempts` as a session variable. Add to it only when a round is won, and divide by `wins` only if `wins > 0`.
+:::
+
+### 5. The computer guesses your number
+
+Reverse the game: the player thinks of a number from 1 to 100, and the computer guesses. The player answers `h` (too high), `l` (too low), or `c` (correct). The computer should always win within 7 guesses and should detect cheating (for example, answers that make `low` bigger than `high`).
+
+::: details Hints
+- Keep `low = 1` and `high = 100`. The computer guesses `(low + high) // 2`.
+- On `h`, set `high = guess - 1`. On `l`, set `low = guess + 1`.
+- If `low > high`, the player gave inconsistent answers: print a message and stop.
+- Validate the answer with `match answer:` and `case _:` for anything that is not `h`, `l`, or `c`.
+:::
+
+## Recap
+
+- Plan first: draw the loops and decide which variables live for the whole session and which reset every round.
+- `random.randint(a, b)` includes both ends. `random.seed()` makes results repeatable while testing.
+- Validate before converting: `strip()`, then `isdecimal()`, then `int()`. Use `continue` so bad input does not cost an attempt.
+- A counter plus `while attempts < max_attempts` limits the attempts, and `break` ends the loop early on a win.
+- `match` with `|` patterns turns a menu choice into settings, and `case _:` catches everything else.
+- `break` leaves only the innermost loop, so a flag like `playing` stops the outer loop. Test every path: win, lose, invalid input, and quitting at each prompt.
+
+## Further reading
+
+- [`random.randint` and `random.seed`](https://docs.python.org/3/library/random.html#random.randint)
+- [`str.isdecimal`](https://docs.python.org/3/library/stdtypes.html#str.isdecimal)
+- [Python tutorial: `break` and `continue` statements, and `else` clauses on loops](https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops)
+- [Python tutorial: `match` statements](https://docs.python.org/3/tutorial/controlflow.html#match-statements)
diff --git a/docs/lessons/05-collections/01-lists.md b/docs/lessons/05-collections/01-lists.md
new file mode 100644
index 0000000..df006f2
--- /dev/null
+++ b/docs/lessons/05-collections/01-lists.md
@@ -0,0 +1,506 @@
+---
+title: Lists
+description: "Store ordered collections with lists: creating, indexing, slicing, changing items, adding and removing, looping, and the difference between sharing and copying a list."
+---
+
+# Lists
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- How to create a list and read items by index and slice
+- How lists differ from strings: they can be **changed**
+- How to add items (`append`, `insert`, `extend`, slices) and remove them (`remove`, `pop`, `del`)
+- How to check membership and loop over a list
+- Why `b = a` **shares** a list, and how to make a real copy
+:::
+
+## Why it matters
+
+Programs rarely deal with just one value. A class has many students, a shop has many products, a playlist has many songs. A **list** stores many values in one variable, keeps them **in order**, and lets you add, remove, and change them. It's the most-used collection in Python.
+
+## Creating a list
+
+Put items in square brackets, separated by commas:
+
+```python
+cities = ["Tashkent", "Samarkand", "Bukhara"]
+scores = [88, 92, 79]
+empty = []
+
+print(cities)
+print(len(scores))
+print(len(empty))
+```
+
+```text
+['Tashkent', 'Samarkand', 'Bukhara']
+3
+0
+```
+
+A list can hold any type, even a mix like `["Aziza", 20, True]`, although lists usually hold one kind of item.
+
+You can also make lists from other sequences with `list()`:
+
+```python
+print(list("abc"))
+print(list(range(1, 6)))
+print("red green blue".split())
+```
+
+```text
+['a', 'b', 'c']
+[1, 2, 3, 4, 5]
+['red', 'green', 'blue']
+```
+
+## Indexing and slicing
+
+Lists use exactly the same indexing and slicing as strings (see *Strings* and *String Methods and Slicing*):
+
+```python
+planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter"]
+
+print(planets[0]) # first
+print(planets[-1]) # last
+print(planets[1:3]) # a slice is a new list
+print(planets[::-1]) # reversed copy
+```
+
+```text
+Mercury
+Jupiter
+['Venus', 'Earth']
+['Jupiter', 'Mars', 'Earth', 'Venus', 'Mercury']
+```
+
+## Lists can be changed
+
+{.lesson-diagram width=1536 height=1024 loading=lazy}
+
+Unlike strings, lists are **mutable**. You can replace an item by assigning to its index:
+
+```python
+colors = ["red", "green", "blue"]
+colors[1] = "yellow"
+print(colors)
+```
+
+```text
+['red', 'yellow', 'blue']
+```
+
+You can also assign to a **slice**. That replaces several items at once, and the new part doesn't have to be the same length. Assigning an empty list, or using `del` with a slice, removes items:
+
+```python
+nums = [10, 20, 30, 40, 50, 60]
+nums[1:3] = [21, 31] # replace two items
+print(nums)
+nums[1:3] = [] # remove two items
+print(nums)
+del nums[::2] # delete every second item
+print(nums)
+```
+
+```text
+[10, 21, 31, 40, 50, 60]
+[10, 40, 50, 60]
+[40, 60]
+```
+
+## Adding items
+
+| Method | What it does |
+|---|---|
+| `lst.append(x)` | Add `x` to the **end** |
+| `lst.insert(i, x)` | Insert `x` **at position** `i` (later items shift right) |
+| `lst.extend(other)` | Add **every item** from another sequence to the end |
+
+```python
+queue = ["Aziza", "Bekzod"]
+
+queue.append("Dilnoza")
+queue.insert(0, "Farrukh")
+queue.extend(["Gulnora", "Hasan"])
+
+print(queue)
+```
+
+```text
+['Farrukh', 'Aziza', 'Bekzod', 'Dilnoza', 'Gulnora', 'Hasan']
+```
+
+`append` is the one you'll use most. A common pattern is the **filter** from *Common Loop Patterns*: start with an empty list and append only the items you want to keep:
+
+```python
+scores = [72, 95, 58, 88, 64, 91]
+
+high_scores = []
+for score in scores:
+ if score >= 85:
+ high_scores.append(score)
+print(high_scores)
+```
+
+```text
+[95, 88, 91]
+```
+
+::: warning append vs extend
+`queue.append(["x", "y"])` adds **one** item, the whole list, creating a list inside a list. `queue.extend(["x", "y"])` adds **two** items.
+:::
+
+## Removing items
+
+| Way | What it does |
+|---|---|
+| `lst.remove(x)` | Remove the **first item equal to** `x` |
+| `lst.pop()` | Remove the **last** item and return it |
+| `lst.pop(i)` | Remove the item **at index** `i` and return it |
+| `del lst[i]` | Delete the item at index `i` (also works with slices) |
+| `lst.clear()` | Remove **everything** |
+
+```python
+tasks = ["email", "meeting", "lunch", "report", "call"]
+
+tasks.remove("lunch") # by value
+last = tasks.pop() # remove and keep the last item
+first = tasks.pop(0) # remove and keep the first item
+del tasks[0] # delete by index
+
+print(tasks)
+print(f"Popped: {first}, {last}")
+```
+
+```text
+['report']
+Popped: email, call
+```
+
+Use `remove` when you know the **value**, and `pop` or `del` when you know the **position**. Use `pop` when you also need the removed item.
+
+### Stacks and queues
+
+With `append` and `pop()`, a list is a **stack**: last in, first out, like a browser's Back button. With `pop(0)` it's a **queue**: first come, first served.
+
+```python
+history = ["home", "news"]
+history.append("weather")
+print(history.pop(), history) # stack: take the newest
+
+line = ["Aziza", "Bekzod"]
+line.append("Dilnoza")
+print(line.pop(0), line) # queue: take the oldest
+```
+
+```text
+weather ['home', 'news']
+Aziza ['Bekzod', 'Dilnoza']
+```
+
+`pop(0)` shifts every remaining item left, which is slow for long lists. For big queues, use `collections.deque` and its fast `popleft()`.
+
+## Checking and searching
+
+```python
+fruits = ["apple", "banana", "cherry", "banana"]
+
+print("banana" in fruits)
+print("mango" not in fruits)
+print(fruits.index("banana")) # position of the first match
+print(fruits.count("banana"))
+```
+
+```text
+True
+True
+1
+2
+```
+
+`.index()` raises a `ValueError` if the item isn't there, so check with `in` first if you're not sure.
+
+## Looping over a list
+
+```python
+prices = [12000, 4500, 30000]
+
+for price in prices:
+ print(f"{price:,} som")
+```
+
+With positions, use `enumerate()` (from *Common Loop Patterns*):
+
+```python
+guests = ["Aziza", "Bekzod", "Dilnoza"]
+
+for seat, guest in enumerate(guests, start=1):
+ print(f"Seat {seat}: {guest}")
+```
+
+```text
+Seat 1: Aziza
+Seat 2: Bekzod
+Seat 3: Dilnoza
+```
+
+## Combining lists
+
+```python
+a = [1, 2]
+b = [3, 4]
+
+print(a + b) # new list
+print(a * 3) # repeated
+```
+
+```text
+[1, 2, 3, 4]
+[1, 2, 1, 2, 1, 2]
+```
+
+`+` creates a **new** list and leaves `a` and `b` unchanged. `extend` changes the list in place.
+
+## Sharing vs. copying
+
+This is the most important idea in this lesson. Remember from *Variables* that names are **labels**. With lists, that matters, because a list can change:
+
+```python
+original = ["tea", "coffee"]
+same_list = original # a second label for the SAME list
+
+same_list.append("juice")
+
+print(original)
+print(same_list)
+```
+
+```text
+['tea', 'coffee', 'juice']
+['tea', 'coffee', 'juice']
+```
+
+`same_list = original` didn't copy anything. Both names refer to **one** list, so changing it through either name changes what both see.
+
+To get an independent list, make a **copy**:
+
+```python
+original = ["tea", "coffee"]
+copy_1 = original.copy()
+copy_2 = original[:] # a full slice also copies
+copy_3 = list(original)
+
+copy_1.append("juice")
+
+print(original)
+print(copy_1)
+```
+
+```text
+['tea', 'coffee']
+['tea', 'coffee', 'juice']
+```
+
+`copy_1 is original` is `False`: `is` asks "the same list?", while `==` only compares contents.
+
+::: info Shallow copies
+These copies are **shallow**: if the list contains other lists, the inner lists are still shared. The *Nested Data* lesson explains this.
+:::
+
+## Try it
+
+A to-do list manager. Try adding, removing, and marking tasks as done.
+
+
+
+## Common mistakes
+
+### 1. Index out of range
+
+```py
+items = ["a", "b", "c"]
+print(items[3])
+```
+
+```text
+IndexError: list index out of range
+```
+
+The last index is `len(items) - 1`.
+
+### 2. Removing something that isn't there
+
+```py
+items = ["a", "b"]
+items.remove("z")
+```
+
+```text
+ValueError: list.remove(x): x not in list
+```
+
+**Fix:** `if "z" in items: items.remove("z")`.
+
+### 3. Assigning the result of `append`
+
+```python
+numbers = [1, 2]
+numbers = numbers.append(3)
+print(numbers)
+```
+
+```text
+None
+```
+
+List methods like `append`, `insert`, `extend`, `remove`, and `sort` change the list **in place** and return `None`. **Fix:** just call `numbers.append(3)`.
+
+### 4. Removing items while looping over the same list
+
+```python
+numbers = [1, 2, 2, 3]
+for n in numbers:
+ if n == 2:
+ numbers.remove(n)
+print(numbers)
+```
+
+```text
+[1, 2, 3]
+```
+
+One `2` survived.
+Removing shifts the remaining items left, so the loop skips the item that moved into the removed one's place. **Fix:** loop over a copy (`for n in numbers[:]:`) or build a new list with only the items you want to keep.
+
+## Practice
+
+### 1. Favorite foods
+
+Create a list of three favorite foods. Print the first and the last, then add one more to the end and print the whole list and its length.
+
+::: details Solution
+```python
+foods = ["plov", "manti", "shashlik"]
+print(foods[0], foods[-1])
+
+foods.append("lagman")
+print(foods, len(foods))
+```
+:::
+
+### 2. Replace and remove
+
+Starting from `week = ["Mon", "Tue", "Wednesday", "Thu", "Fri", "Sat", "Sun"]`, replace `"Wednesday"` with `"Wed"`, then remove the weekend days so only workdays remain.
+
+::: details Solution
+```python
+week = ["Mon", "Tue", "Wednesday", "Thu", "Fri", "Sat", "Sun"]
+
+week[2] = "Wed"
+del week[5:] # delete from index 5 to the end
+
+print(week)
+```
+
+```text
+['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
+```
+:::
+
+### 3. Remove the negatives
+
+Remove every negative number from `numbers = [3, -1, -2, 4, -5]`, changing that list in place. First run the naive loop below and explain why it prints `[3, -2, 4]`. Then fix it so it prints `[3, 4]`.
+
+```py
+numbers = [3, -1, -2, 4, -5]
+for n in numbers:
+ if n < 0:
+ numbers.remove(n)
+print(numbers)
+```
+
+::: details Solution
+When `-1` is removed, `-2` slides into its position, and the loop moves on to the next position, so it never sees `-2`. Loop over a **copy** instead, so removing items from `numbers` doesn't shift what the loop visits:
+
+```python
+numbers = [3, -1, -2, 4, -5]
+for n in numbers[:]:
+ if n < 0:
+ numbers.remove(n)
+print(numbers)
+```
+
+```text
+[3, 4]
+```
+:::
+
+### 4. Predict the sharing
+
+Predict what this prints, then run it.
+
+```python
+a = [1, 2, 3]
+b = a
+c = a[:]
+b.append(4)
+c.append(5)
+a[0] = 99
+print(a)
+print(b)
+print(c)
+```
+
+::: details Solution
+```text
+[99, 2, 3, 4]
+[99, 2, 3, 4]
+[1, 2, 3, 5]
+```
+
+`a` and `b` are the same list, so both see `4` and `99`. `c` was copied before any changes and only got `5`.
+:::
+
+### 5. Rotate a list
+
+Rotate `numbers = [1, 2, 3, 4, 5]` to the right by `k = 2` positions, so it becomes `[4, 5, 1, 2, 3]`. Solve it twice: once with slicing, and once with a loop using `pop()` and `insert()`. Make sure it also works when `k` is bigger than the length (for example `k = 7`).
+
+::: details Solution
+```python
+numbers = [1, 2, 3, 4, 5]
+k = 7
+
+# 1. Slicing
+shift = k % len(numbers) # 7 % 5 = 2
+rotated = numbers[-shift:] + numbers[:-shift]
+print(rotated)
+
+# 2. pop and insert (changes the list in place)
+for _ in range(shift):
+ last = numbers.pop()
+ numbers.insert(0, last)
+print(numbers)
+```
+
+```text
+[4, 5, 1, 2, 3]
+[4, 5, 1, 2, 3]
+```
+
+`k % len(numbers)` handles large `k`, because rotating 5 times brings the list back to where it started. A `shift` of `0` still works: `numbers[-0:]` is the whole list and `numbers[:-0]` is empty, so nothing moves. The real edge case is an empty list, where `k % len(numbers)` raises `ZeroDivisionError`.
+:::
+
+## Recap
+
+- A list is an **ordered, changeable** sequence: `items = [a, b, c]`.
+- Indexing and slicing work as they do for strings, and `items[i] = x` replaces an item.
+- Add with `append`, `insert`, `extend`, or slice assignment. Remove with `remove` (by value), `pop` and `del` (by position), and `clear`. These change the list **in place** and return `None`.
+- `append` + `pop()` makes a stack, and `pop(0)` a queue. Don't remove items from a list while looping over it.
+- `b = a` shares one list. Use `a.copy()` or `a[:]` for an independent copy.
+
+## Further reading
+
+- [Python Tutorial - Lists](https://docs.python.org/3/tutorial/introduction.html#lists)
+- [More on lists (methods)](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists)
+- [Sequence types - `list`](https://docs.python.org/3/library/stdtypes.html#lists)
diff --git a/docs/lessons/05-collections/02-list-operations-and-sorting.md b/docs/lessons/05-collections/02-list-operations-and-sorting.md
new file mode 100644
index 0000000..09167a4
--- /dev/null
+++ b/docs/lessons/05-collections/02-list-operations-and-sorting.md
@@ -0,0 +1,476 @@
+---
+title: Working with Lists and Sorting
+description: "Sort lists with sort() and sorted(), control the order with reverse and key, use min, max, and sum, and handle common list tasks like removing duplicates and joining."
+---
+
+# Working with Lists and Sorting
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- The difference between `list.sort()` and `sorted()`
+- How to sort in reverse and with a **key** function
+- How to sort text alphabetically regardless of capitals
+- Built-ins for lists: `min`, `max`, `sum`, `len`, `reversed`
+- Everyday list tasks: removing duplicates, finding positions, and joining into text
+:::
+
+## Why it matters
+
+Once data is in a list, you usually want to **organize** it: rank scores from highest to lowest, list names alphabetically, show the cheapest products first. Python's sorting is fast, flexible, and takes just one line, once you know how to tell it *what* to sort by.
+
+## `sort()` vs `sorted()`
+
+There are two ways to sort, and the difference matters:
+
+```python
+scores = [72, 95, 58, 88]
+
+ranked = sorted(scores) # returns a NEW sorted list
+print(ranked)
+print(scores) # original unchanged
+
+scores.sort() # sorts the list IN PLACE, returns None
+print(scores)
+```
+
+```text
+[58, 72, 88, 95]
+[72, 95, 58, 88]
+[58, 72, 88, 95]
+```
+
+| | `sorted(items)` | `items.sort()` |
+|---|---|---|
+| Changes the original? | No | **Yes** |
+| Returns | a new list | `None` |
+| Works on | any iterable: lists, strings, tuples, sets, dicts… | lists only |
+
+Use `sorted()` when you want to keep the original order too. Use `.sort()` when you don't need it anymore.
+
+`sorted()` works on any iterable, and always returns a list:
+
+```python
+print(sorted("python"))
+print(sorted((3, 1, 2)))
+```
+
+```text
+['h', 'n', 'o', 'p', 't', 'y']
+[1, 2, 3]
+```
+
+## Reverse order
+
+Both accept `reverse=True`:
+
+```python
+scores = [72, 95, 58, 88]
+
+print(sorted(scores, reverse=True))
+
+scores.sort(reverse=True)
+print(scores)
+```
+
+```text
+[95, 88, 72, 58]
+[95, 88, 72, 58]
+```
+
+Don't confuse this with `.reverse()`, which just flips the current order **without sorting**:
+
+```python
+letters = ["b", "c", "a"]
+letters.reverse()
+print(letters)
+```
+
+```text
+['a', 'c', 'b']
+```
+
+## Sorting text
+
+Strings sort by character codes (see *Booleans and Comparisons*), so **all uppercase letters come before lowercase**:
+
+```python
+names = ["bekzod", "Aziza", "dilnoza", "Charos"]
+print(sorted(names))
+```
+
+```text
+['Aziza', 'Charos', 'bekzod', 'dilnoza']
+```
+
+That's rarely what people expect. The fix is a **key**.
+
+## Sorting with a key
+
+`key=` tells Python **what to compare** for each item. You pass a function, and Python calls it on every item and sorts by the results. The items themselves stay the same.
+
+```python
+names = ["bekzod", "Aziza", "dilnoza", "Charos"]
+
+print(sorted(names, key=str.lower)) # compare lowercase versions
+```
+
+```text
+['Aziza', 'bekzod', 'Charos', 'dilnoza']
+```
+
+Notice there are **no parentheses** after `str.lower`. You're handing over the function itself, for `sorted` to call, not calling it yourself.
+
+Other useful keys:
+
+```python
+words = ["banana", "fig", "cherry", "kiwi"]
+print(sorted(words, key=len)) # by length
+
+temperatures = [-12, 5, -3, 8, 0]
+print(sorted(temperatures, key=abs)) # by distance from zero
+```
+
+```text
+['fig', 'kiwi', 'banana', 'cherry']
+[0, -3, 5, 8, -12]
+```
+
+When two items have the **same key**, like `"banana"` and `"cherry"` (both 6 letters), they keep their original relative order. Python's sort is **stable**.
+
+You can combine `key` and `reverse`:
+
+```python
+words = ["banana", "fig", "cherry", "kiwi"]
+print(sorted(words, key=len, reverse=True))
+```
+
+```text
+['banana', 'cherry', 'kiwi', 'fig']
+```
+
+::: info Custom keys
+Soon you'll write your own key functions, including short one-line ones called `lambda`s (see *Lambdas and Higher-Order Functions*). For example, `key=lambda p: p["price"]` sorts products by price. To sort by **several** things, a key can return a pair: `key=lambda p: (p["category"], p["price"])` sorts by category, then by price within each category.
+:::
+
+## min, max, sum, and friends
+
+```python
+prices = [12000, 4500, 30000, 8000]
+
+print(min(prices))
+print(max(prices))
+print(sum(prices))
+print(sum(prices) / len(prices))
+```
+
+```text
+4500
+30000
+54500
+13625.0
+```
+
+`min` and `max` also accept a `key`:
+
+```python
+words = ["banana", "fig", "cherry", "kiwi"]
+print(max(words, key=len))
+print(min(words, key=len))
+```
+
+```text
+banana
+fig
+```
+
+If several items tie, the **first** one wins.
+
+## More list methods
+
+| Method | What it does |
+|---|---|
+| `lst.index(x)` | position of the first `x` (`ValueError` if missing) |
+| `lst.count(x)` | how many times `x` appears |
+| `lst.reverse()` | reverse in place |
+| `lst.copy()` | shallow copy |
+
+And some useful built-ins:
+
+| Function | What it does |
+|---|---|
+| `len(lst)` | number of items |
+| `reversed(lst)` | items in reverse order, for looping |
+| `sorted(lst)` | new sorted list |
+| `any(...)`, `all(...)` | yes/no checks (see *Comprehensions*) |
+
+## Common list tasks
+
+### Is the list empty?
+
+An empty list is falsy:
+
+```python
+cart = []
+
+if not cart:
+ print("Your cart is empty")
+```
+
+### Top N items
+
+Sort, then slice:
+
+```python
+scores = [72, 95, 58, 88, 64, 91]
+
+top_three = sorted(scores, reverse=True)[:3]
+print(top_three)
+```
+
+```text
+[95, 91, 88]
+```
+
+### Removing duplicates while keeping order
+
+```python
+visits = ["home", "about", "home", "shop", "about", "home"]
+
+unique = []
+for page in visits:
+ if page not in unique:
+ unique.append(page)
+
+print(unique)
+```
+
+```text
+['home', 'about', 'shop']
+```
+
+For large lists, the *Sets* lesson shows faster ways.
+
+### Joining a list into text
+
+`.join()` only works with strings. A common pattern is to collect the pieces as strings in a list, then join them once at the end:
+
+```python
+numbers = [3, 1, 4, 1, 5]
+
+parts = []
+for n in numbers:
+ parts.append(str(n))
+print(", ".join(parts))
+```
+
+```text
+3, 1, 4, 1, 5
+```
+
+*Comprehensions* shows a one-line version: `", ".join(str(n) for n in numbers)`.
+
+### Sorting parallel lists together
+
+If names and scores are in two separate lists, sort the **pairs**, so they stay together:
+
+```python
+names = ["Aziza", "Bekzod", "Dilnoza"]
+marks = [81, 94, 88]
+
+for mark, name in sorted(zip(marks, names), reverse=True):
+ print(f"{name}: {mark}")
+```
+
+```text
+Bekzod: 94
+Dilnoza: 88
+Aziza: 81
+```
+
+`zip(marks, names)` produces pairs like `(81, "Aziza")`. Pairs sort by their first item, the mark, and only look at the second item when the marks are equal. You'll learn more about these pairs (*tuples*) in the next lesson.
+
+## Try it
+
+Sort the product names in different ways. Try `key=len`, `reverse=True`, or sorting by price.
+
+
+
+## Common mistakes
+
+### 1. Saving the result of `.sort()`
+
+```python
+scores = [3, 1, 2]
+scores = scores.sort()
+print(scores)
+```
+
+```text
+None
+```
+
+**Fix:** either `scores.sort()` on its own line, or `scores = sorted(scores)`.
+
+### 2. Sorting mixed types
+
+```py
+values = [10, "5", 3]
+values.sort()
+```
+
+```text
+TypeError: '<' not supported between instances of 'str' and 'int'
+```
+
+Python won't guess how to order a string against a number. **Fix:** convert everything to one type first.
+
+### 3. Calling the key function
+
+```py
+names = ["b", "A"]
+sorted(names, key=str.lower())
+```
+
+```text
+TypeError: unbound method str.lower() needs an argument
+```
+
+Pass the function itself, without parentheses: `key=str.lower`.
+
+### 4. `min()` or `max()` of an empty list
+
+```py
+max([])
+```
+
+```text
+ValueError: max() iterable argument is empty
+```
+
+Check that the list isn't empty, or give a default: `max(values, default=0)`.
+
+## Practice
+
+### 1. Alphabetical guests
+
+Print `guests = ["zafar", "Aziza", "madina", "Bobur"]` in alphabetical order, ignoring capitals, with each name capitalized.
+
+::: details Solution
+```python
+guests = ["zafar", "Aziza", "madina", "Bobur"]
+
+for guest in sorted(guests, key=str.lower):
+ print(guest.capitalize())
+```
+:::
+
+### 2. Stats
+
+For `temps = [31, 35, 28, 37, 33, 26, 30]`, print the lowest, highest, average (1 decimal), and the temperatures sorted from hottest to coldest.
+
+::: details Solution
+```python
+temps = [31, 35, 28, 37, 33, 26, 30]
+
+print(f"Lowest: {min(temps)}")
+print(f"Highest: {max(temps)}")
+print(f"Average: {sum(temps) / len(temps):.1f}")
+print(f"Hottest first: {sorted(temps, reverse=True)}")
+```
+:::
+
+### 3. Median
+
+The **median** is the middle value of a sorted list. For an even number of items, it's the average of the two middle values. Calculate the median of `[7, 1, 5, 3]` (answer `4.0`) and `[9, 2, 6]` (answer `6`).
+
+::: details Solution
+```python
+for values in [[7, 1, 5, 3], [9, 2, 6]]:
+ ordered = sorted(values)
+ middle = len(ordered) // 2
+
+ if len(ordered) % 2 == 1:
+ median = ordered[middle]
+ else:
+ median = (ordered[middle - 1] + ordered[middle]) / 2
+
+ print(median)
+```
+:::
+
+### 4. Word frequency ranking
+
+For `text = "the cat and the dog and the bird"`, print each **unique** word with how many times it appears, most frequent first. Use `.count()` and a list of unique words.
+
+::: details Solution
+```python
+text = "the cat and the dog and the bird"
+words = text.split()
+
+unique = []
+for word in words:
+ if word not in unique:
+ unique.append(word)
+
+for count, word in sorted(zip([words.count(w) for w in unique], unique), reverse=True):
+ print(f"{word}: {count}")
+```
+
+```text
+the: 3
+and: 2
+dog: 1
+cat: 1
+bird: 1
+```
+
+Words with the same count are sorted by the word itself in reverse, because pairs compare their second item when the first items are equal. `[words.count(w) for w in unique]` is a list comprehension, explained in *Comprehensions*. The *Dictionaries* lesson shows a more efficient way to count.
+:::
+
+### 5. Leaderboard
+
+Given:
+
+```python
+players = ["ali", "Vali", "gani", "Sami", "Doni"]
+points = [120, 95, 120, 150, 95]
+```
+
+Print a leaderboard sorted by **points, highest first**. When points are equal, sort by **name alphabetically**, ignoring case. Show ranks starting from 1:
+
+```text
+1. Sami 150
+2. ali 120
+3. gani 120
+4. Doni 95
+5. Vali 95
+```
+
+::: details Solution
+```python
+players = ["ali", "Vali", "gani", "Sami", "Doni"]
+points = [120, 95, 120, 150, 95]
+
+pairs = sorted(zip(players, points), key=lambda pair: (-pair[1], pair[0].lower()))
+
+for rank, (name, score) in enumerate(pairs, start=1):
+ print(f"{rank}. {name:<5}{score:>4}")
+```
+
+`lambda pair: ...` is a tiny inline function (see *Lambdas and Higher-Order Functions*). The key returns a pair: minus the points, so higher points come first, then the lowercase name, which breaks ties. This is what people usually write. Another way uses stability: sort by name first, then `sort(key=..., reverse=True)` by points, and the names stay alphabetical within each points group.
+:::
+
+## Recap
+
+- `sorted(items)` returns a new list. `items.sort()` sorts in place and returns `None`.
+- `reverse=True` sorts descending. `.reverse()` just flips the order.
+- `key=function` sorts by a computed value: `key=str.lower`, `key=len`, `key=abs`. Pass the function without `()`. The sort is **stable**, so equal keys keep their order.
+- `min`, `max`, `sum`, and `len` summarize lists, and `min`/`max` accept `key` and `default`.
+- Top N: `sorted(items, reverse=True)[:n]`. Keep related lists together by sorting `zip()` pairs.
+
+## Further reading
+
+- [Sorting techniques (HOWTO)](https://docs.python.org/3/howto/sorting.html)
+- [Built-in functions - `sorted()`](https://docs.python.org/3/library/functions.html#sorted)
+- [`list.sort()`](https://docs.python.org/3/library/stdtypes.html#list.sort)
diff --git a/docs/lessons/05-collections/03-tuples-and-unpacking.md b/docs/lessons/05-collections/03-tuples-and-unpacking.md
new file mode 100644
index 0000000..4ce4b82
--- /dev/null
+++ b/docs/lessons/05-collections/03-tuples-and-unpacking.md
@@ -0,0 +1,531 @@
+---
+title: Tuples and Unpacking
+description: "Group fixed values with tuples, unpack sequences into variables, collect extra values with *, and learn when to choose a tuple over a list."
+---
+
+# Tuples and Unpacking
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- How to create a **tuple**, including the one-item tuple
+- Why tuples can't be changed, and how tuples compare
+- How to **unpack** a sequence into separate variables
+- How `*rest` collects "everything else"
+- When to use a tuple instead of a list
+:::
+
+## Why it matters
+
+Some groups of values belong together and shouldn't change: a point's `(x, y)` coordinates, an RGB color `(255, 128, 0)`, a date `(2026, 9, 15)`. A **tuple** stores such a fixed group. Together with **unpacking**, tuples make code shorter and clearer, and you've already been using them without noticing, in `a, b = b, a`, `enumerate()`, and `zip()`.
+
+## Creating a tuple
+
+Put values in parentheses, separated by commas:
+
+```python
+point = (3, 4)
+color = (255, 128, 0)
+birthday = (2004, 3, 21)
+
+print(point)
+print(type(color))
+print(len(birthday))
+```
+
+```text
+(3, 4)
+
+3
+```
+
+Actually, the **comma** makes the tuple, not the parentheses. The parentheses are usually added for readability:
+
+```python
+size = 1920, 1080
+print(size)
+```
+
+```text
+(1920, 1080)
+```
+
+### Empty and one-item tuples
+
+```python
+empty = ()
+single = ("tea",) # the trailing comma is required
+not_a_tuple = ("tea") # just a string in parentheses
+
+print(type(single))
+print(type(not_a_tuple))
+```
+
+```text
+
+
+```
+
+## Reading tuples
+
+Tuples support everything that doesn't change them: indexing, slicing, `len`, `in`, `count`, `index`, and loops.
+
+```python
+weekdays = ("Mon", "Tue", "Wed", "Thu", "Fri")
+
+print(weekdays[0])
+print(weekdays[-2:])
+print("Sat" in weekdays)
+
+for day in weekdays:
+ print(day, end=" ")
+print()
+```
+
+```text
+Mon
+('Thu', 'Fri')
+False
+Mon Tue Wed Thu Fri
+```
+
+### Comparing tuples
+
+Tuples compare **item by item**, like words in a dictionary: the first items decide, and only if they're equal does Python look at the second, and so on.
+
+```python
+print((1, "b") < (1, "c"))
+print((2026, 3, 21) < (2026, 12, 1))
+print(sorted([("Bekzod", 85), ("Aziza", 92), ("Aziza", 78)]))
+```
+
+```text
+True
+True
+[('Aziza', 78), ('Aziza', 92), ('Bekzod', 85)]
+```
+
+That's why `sorted(zip(marks, names))` in *Working with Lists and Sorting* sorted by mark first, and why dates stored as `(year, month, day)` sort correctly.
+
+## Tuples are immutable
+
+```py
+point = (3, 4)
+point[0] = 10
+```
+
+```text
+TypeError: 'tuple' object does not support item assignment
+```
+
+There's no `append`, `remove`, or `sort` either. To "change" a tuple, create a new one:
+
+```python
+point = (3, 4)
+point = (10, point[1])
+print(point)
+```
+
+```text
+(10, 4)
+```
+
+Why is that useful?
+
+- **Safety:** you can't replace or remove a tuple's items by accident.
+- **Meaning:** a tuple says "this is one fixed record", while a list says "this is a collection that may grow".
+- **Dictionary keys:** tuples of immutable values (numbers, strings, other such tuples) can be used as keys in dictionaries and as items in sets. Lists can't. (See *Dictionaries* and *Sets*.)
+
+```python
+distances = {("Tashkent", "Samarkand"): 300, ("Tashkent", "Bukhara"): 570}
+print(distances[("Tashkent", "Bukhara")])
+```
+
+```text
+570
+```
+
+### Immutable, but only one level deep
+
+A tuple fixes *which* objects it holds, not what happens inside them. If one item is a list, that list can still change, and the tuple can no longer be a dictionary key:
+
+```python
+team = ("Aziza", ["Bekzod"])
+team[1].append("Dilnoza")
+print(team)
+
+try:
+ groups = {team: "Group A"}
+except TypeError as error:
+ print("TypeError:", error)
+```
+
+```text
+('Aziza', ['Bekzod', 'Dilnoza'])
+TypeError: cannot use 'tuple' as a dict key (unhashable type: 'list')
+```
+
+## Unpacking
+
+**Unpacking** assigns the items of a sequence to several variables at once:
+
+```python
+point = (3, 4)
+x, y = point
+
+print(f"x = {x}, y = {y}")
+```
+
+```text
+x = 3, y = 4
+```
+
+It works with any iterable: tuples, lists, strings, and the results of `.split()`:
+
+```python
+first, last = "Aziza Karimova".split()
+day, month, year = "15/09/2026".split("/")
+a, b, c = "xyz"
+
+print(last, year, c)
+```
+
+```text
+Karimova 2026 z
+```
+
+The number of variables must match the number of items:
+
+```py
+x, y = (1, 2, 3)
+```
+
+```text
+ValueError: too many values to unpack (expected 2, got 3)
+```
+
+### Unpacking in loops
+
+This is where unpacking really shines. You've seen it with `enumerate()` and `zip()`, which produce tuples:
+
+```python
+students = [("Aziza", 92), ("Bekzod", 85), ("Dilnoza", 78)]
+
+for name, score in students:
+ print(f"{name}: {score}")
+```
+
+```text
+Aziza: 92
+Bekzod: 85
+Dilnoza: 78
+```
+
+Compare that with `student[0]` and `student[1]`: the names make the code self-explanatory.
+
+### Swapping
+
+Now you can see how the swap from *Variables* works:
+
+```python
+a, b = 1, 2
+a, b = b, a # the right side builds the tuple (2, 1), then it's unpacked
+print(a, b)
+```
+
+```text
+2 1
+```
+
+### Ignoring values with `_`
+
+Use `_` for values you don't need:
+
+```python
+record = ("Aziza", "Karimova", 20, "Tashkent")
+first_name, _, age, _ = record
+print(first_name, age)
+```
+
+```text
+Aziza 20
+```
+
+## Collecting the rest with `*`
+
+A starred variable collects **all remaining items** into a list:
+
+```python
+scores = [95, 88, 72, 64, 58]
+
+best, *others = scores
+print(best)
+print(others)
+
+*earlier, last = scores
+print(last)
+
+first, *middle, final = scores
+print(middle)
+```
+
+```text
+95
+[88, 72, 64, 58]
+58
+[88, 72, 64]
+```
+
+Only one starred variable is allowed per unpacking. It can collect zero items, in which case it's an empty list.
+
+A handy use is splitting a command from its arguments:
+
+```python
+command, *arguments = "copy report.txt backup.txt".split()
+print(command)
+print(arguments)
+```
+
+```text
+copy
+['report.txt', 'backup.txt']
+```
+
+## Nested unpacking
+
+If items contain tuples, you can unpack the structure in one go:
+
+```python
+route = ("Bus 51", (41.31, 69.28), (41.35, 69.22))
+name, (start_lat, start_lon), (end_lat, end_lon) = route
+print(name, start_lat, end_lon)
+```
+
+```text
+Bus 51 41.31 69.22
+```
+
+The same works in a loop. `enumerate(zip(items, prices))` gives pairs like `(1, ("tea", 15000))`, so the loop variables mirror that shape:
+
+```python
+items = ["tea", "samsa", "juice"]
+prices = [15000, 8000, 12000]
+
+for number, (item, price) in enumerate(zip(items, prices), start=1):
+ print(f"{number}. {item}: {price:,} som")
+```
+
+```text
+1. tea: 15,000 som
+2. samsa: 8,000 som
+3. juice: 12,000 som
+```
+
+## Returning several values
+
+Functions (in the *Functions* module) often return a tuple to give back more than one value, and the caller unpacks it. A built-in example is `divmod()`, which returns the results of `//` and `%` together:
+
+```python
+hours, minutes = divmod(135, 60)
+print(f"{hours} h {minutes} min")
+```
+
+```text
+2 h 15 min
+```
+
+## Tuple or list?
+
+| Use a **tuple** when… | Use a **list** when… |
+|---|---|
+| the number of items is fixed | items will be added or removed |
+| each position has a meaning (x, y), (name, age) | all items are the same kind of thing |
+| the data shouldn't change | you'll sort or modify it |
+| you need a dictionary key or set item | |
+
+A good rule of thumb: a tuple is like **one row** of a table, and a list is like a **whole column**.
+
+## Try it
+
+Unpack each record and print a formatted table. Then add a new record.
+
+
+
+## Common mistakes
+
+### 1. Forgetting the comma in a one-item tuple
+
+```python
+colors = ("red")
+print(type(colors))
+```
+
+```text
+
+```
+
+The parentheses alone do nothing. **Fix:** `colors = ("red",)`.
+
+### 2. `zip()` silently dropping items
+
+```python
+names = ["Aziza", "Bekzod", "Dilnoza"]
+marks = [92, 85]
+for name, mark in zip(names, marks):
+ print(name, mark)
+```
+
+```text
+Aziza 92
+Bekzod 85
+```
+
+Dilnoza vanished without any error: `zip()` stops at the shortest input. **Fix:** pass `strict=True`, so a length mismatch raises an error once the shorter list runs out:
+
+```text
+ValueError: zip() argument 2 is shorter than argument 1
+```
+
+### 3. Wrong number of variables
+
+```py
+name, age = ("Aziza", 20, "Tashkent")
+```
+
+```text
+ValueError: too many values to unpack (expected 2, got 3)
+```
+
+With too few values, the message is `not enough values to unpack`. **Fix:** match the count, or use `*rest` or `_`.
+
+### 4. Unpacking a string by accident
+
+```python
+first, second = "ab" # works: 'a' and 'b'
+print(first)
+```
+
+```py
+first, second = "abc"
+```
+
+```text
+ValueError: too many values to unpack (expected 2)
+```
+
+Strings are sequences of characters, so they unpack character by character. Did you mean to `.split()` first?
+
+## Practice
+
+### 1. Coordinates
+
+Create a tuple `location = (41.2995, 69.2401)` and unpack it into `latitude` and `longitude`. Print them with 2 decimals.
+
+::: details Solution
+```python
+location = (41.2995, 69.2401)
+latitude, longitude = location
+print(f"Latitude: {latitude:.2f}, longitude: {longitude:.2f}")
+```
+:::
+
+### 2. Parse a record
+
+Unpack `"Bekzod,Tursunov,22,Andijan"` (split on commas) into four variables, and print `Bekzod Tursunov (22) from Andijan`.
+
+::: details Solution
+```python
+first, last, age, city = "Bekzod,Tursunov,22,Andijan".split(",")
+print(f"{first} {last} ({age}) from {city}")
+```
+:::
+
+### 3. Distance between points
+
+Given `a = (1, 2)` and `b = (4, 6)`, unpack both and calculate the straight-line distance with `√((x2 − x1)² + (y2 − y1)²)`. The answer is `5.0`.
+
+::: details Solution
+```python
+import math
+
+a = (1, 2)
+b = (4, 6)
+
+x1, y1 = a
+x2, y2 = b
+
+distance = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
+print(distance)
+```
+
+`math.dist(a, b)` does the same calculation directly.
+:::
+
+### 4. Head and tail
+
+Given `race = ["Dilnoza", "Aziza", "Bekzod", "Farrukh", "Gulnora"]` (in finishing order), use starred unpacking to print the winner, the runner-up, and everyone else in one line.
+
+::: details Solution
+```python
+race = ["Dilnoza", "Aziza", "Bekzod", "Farrukh", "Gulnora"]
+
+winner, runner_up, *rest = race
+print(f"Winner: {winner}")
+print(f"Runner-up: {runner_up}")
+print(f"Also finished: {', '.join(rest)}")
+```
+:::
+
+### 5. Grade report from tuples
+
+Given a list of `(name, [scores])` tuples:
+
+```python
+records = [
+ ("Aziza", [90, 85, 97]),
+ ("Bekzod", [72, 64, 80]),
+ ("Dilnoza", [88, 91, 79]),
+]
+```
+
+For each student, print their name, average (1 decimal), best score, and worst score. At the end, print the name of the student with the highest average.
+
+::: details Solution
+```python
+records = [
+ ("Aziza", [90, 85, 97]),
+ ("Bekzod", [72, 64, 80]),
+ ("Dilnoza", [88, 91, 79]),
+]
+
+best_name, best_average = None, 0
+
+for name, scores in records:
+ average = sum(scores) / len(scores)
+ print(f"{name:<8} avg {average:5.1f} best {max(scores)} worst {min(scores)}")
+ if average > best_average:
+ best_name, best_average = name, average
+
+print(f"Top student: {best_name}")
+```
+
+```text
+Aziza avg 90.7 best 97 worst 85
+Bekzod avg 72.0 best 80 worst 64
+Dilnoza avg 86.0 best 91 worst 79
+Top student: Aziza
+```
+:::
+
+## Recap
+
+- A **tuple** is an ordered, **immutable** sequence: `(a, b, c)`. The comma makes it, so write `("x",)` for one item.
+- Tuples support indexing, slicing, `len`, `in`, and loops, but not changes. Tuples of immutable values can be dictionary keys and set items.
+- Tuples compare item by item, which is why sorting pairs sorts by the first item, then the second.
+- **Unpacking** assigns items to variables: `x, y = point`, including in loops. The counts must match, `*rest` collects the rest into a list, and `_` ignores a value.
+- Use tuples for fixed records and lists for collections that change.
+
+## Further reading
+
+- [Python Tutorial - Tuples and sequences](https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences)
+- [PEP 3132 - Extended iterable unpacking](https://peps.python.org/pep-3132/)
diff --git a/docs/lessons/05-collections/04-dictionaries.md b/docs/lessons/05-collections/04-dictionaries.md
new file mode 100644
index 0000000..5028aa8
--- /dev/null
+++ b/docs/lessons/05-collections/04-dictionaries.md
@@ -0,0 +1,489 @@
+---
+title: Dictionaries
+description: "Store and look up data by key with Python dictionaries: create, read, update, loop, and use common patterns like counting and grouping."
+---
+
+# Dictionaries
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- Create a dictionary and read values by **key**
+- Add, change, and remove entries safely
+- Avoid `KeyError` with `in` and `.get()`
+- Loop over keys, values, and key-value pairs
+- Use two everyday patterns: **counting** and **grouping**
+:::
+
+## Why it matters
+
+A list is good when order matters and you find items by position: the *first* runner, the *third* song. But real data usually has names. You look up a contact by *name*, not by "contact number 47". A product price is found by *product*, and a word's definition by *the word*.
+
+A **dictionary** (`dict`) stores data as **key → value** pairs. You give it a key and it gives back the value, fast, however big the dictionary is.
+
+```python
+prices = {"apple": 1.20, "bread": 2.50, "milk": 0.99}
+print(prices["bread"])
+```
+
+```text
+2.5
+```
+
+## Creating a dictionary
+
+Write pairs inside curly braces. Put a colon between each key and its value, and separate pairs with commas:
+
+```python
+student = {
+ "name": "Aziza",
+ "age": 20,
+ "courses": ["Math", "Physics"],
+}
+print(student)
+```
+
+For long dictionaries, put one pair per line with a trailing comma.
+
+An empty dictionary is just `{}`. You'll often start empty and fill it up as the program runs.
+
+The `dict()` constructor builds a dictionary from keyword arguments, or from pairs. `zip()` makes those pairs from two lists:
+
+```python
+student = dict(name="Aziza", age=20)
+print(student)
+
+cities = ["Tashkent", "Samarkand", "Bukhara"]
+people = [2956000, 551000, 280000]
+print(dict(zip(cities, people)))
+```
+
+```text
+{'name': 'Aziza', 'age': 20}
+{'Tashkent': 2956000, 'Samarkand': 551000, 'Bukhara': 280000}
+```
+
+**Keys and values have different rules:**
+
+| | Can be | Examples |
+|---|---|---|
+| **Key** | Unique, and an immutable (hashable) type | `"name"`, `42`, `(3, 4)` |
+| **Value** | Anything at all | numbers, strings, lists, other dicts |
+
+Keys are unique. If you write the same key twice, the last value wins:
+
+```python
+colors = {"sky": "blue", "grass": "green", "sky": "grey"}
+print(colors)
+```
+
+```text
+{'sky': 'grey', 'grass': 'green'}
+```
+
+## Reading values
+
+### Square brackets: `d[key]`
+
+```python
+student = {"name": "Aziza", "age": 20}
+print(student["name"])
+```
+
+If the key doesn't exist, Python raises a `KeyError`. That's useful when a missing key really is a bug, because the program stops right where the problem is.
+
+### Checking first: `key in d`
+
+The `in` operator checks whether a **key** exists:
+
+```python
+student = {"name": "Aziza", "age": 20}
+
+if "email" in student:
+ print(student["email"])
+else:
+ print("No email on file")
+```
+
+### A default value: `d.get(key, default)`
+
+`.get()` returns the value if the key exists. If it doesn't, you get the default (or `None` if you didn't give one). It never raises `KeyError`:
+
+```python
+student = {"name": "Aziza", "age": 20}
+
+print(student.get("age"))
+print(student.get("email"))
+print(student.get("email", "not provided"))
+```
+
+```text
+20
+None
+not provided
+```
+
+**Which one should you use?**
+- Use `d[key]` when the key *must* be there. A crash tells you something is wrong.
+- Use `d.get(key, default)` when a missing key is normal, for example an optional field.
+
+## Adding, changing, and removing
+
+Assignment adds a key if it's new and replaces the value if it already exists:
+
+```python
+stock = {"apple": 10}
+
+stock["banana"] = 25 # add
+stock["apple"] = 7 # change
+stock["apple"] += 3 # update using the old value
+
+print(stock)
+```
+
+```text
+{'apple': 10, 'banana': 25}
+```
+
+There are three common ways to remove an entry:
+
+```python
+stock = {"apple": 10, "banana": 25, "cherry": 40}
+
+del stock["apple"] # remove; KeyError if missing
+count = stock.pop("banana") # remove AND return the value
+missing = stock.pop("kiwi", 0) # default instead of KeyError
+
+print(stock, count, missing)
+```
+
+```text
+{'cherry': 40} 25 0
+```
+
+To combine two dictionaries, use `|`. It builds a new dictionary, and keys from the right side win:
+
+```python
+defaults = {"theme": "light", "font_size": 14}
+user_choice = {"theme": "dark"}
+
+config = defaults | user_choice
+print(config)
+```
+
+```text
+{'theme': 'dark', 'font_size': 14}
+```
+
+`defaults.update(user_choice)` does the same thing but changes `defaults` in place.
+
+## Looping over a dictionary
+
+A dictionary remembers the order you inserted keys in. Pick the loop that matches what you need:
+
+```python
+scores = {"Aziza": 92, "Bekzod": 78, "Dilnoza": 85}
+
+for name in scores: # keys (same as scores.keys())
+ print(name)
+
+for score in scores.values(): # values only
+ print(score)
+
+for name, score in scores.items(): # both, unpacked
+ print(f"{name}: {score}")
+```
+
+`.items()` gives you `(key, value)` pairs, and `for name, score in ...` unpacks each pair into two variables. This is the loop you'll use most.
+
+To go through keys in sorted order, or sort by value:
+
+```python
+scores = {"Aziza": 92, "Bekzod": 78, "Dilnoza": 85}
+
+for name in sorted(scores):
+ print(name, scores[name])
+
+best = max(scores, key=scores.get)
+print("Top student:", best)
+```
+
+`max(scores, key=scores.get)` looks at every key but compares them by their values.
+
+### Views: live, but not lists
+
+`.keys()`, `.values()`, and `.items()` don't return lists. They return **views**: windows onto the dictionary that update when it changes. A view can't be indexed, so wrap it in `list()` when you need positions or a snapshot:
+
+```python
+scores = {"Aziza": 92, "Bekzod": 78}
+names = scores.keys()
+
+scores["Dilnoza"] = 85
+print(names) # the view saw the new key
+print(list(names)[0]) # names[0] would raise TypeError
+```
+
+```text
+dict_keys(['Aziza', 'Bekzod', 'Dilnoza'])
+Aziza
+```
+
+`list(scores)` gives the keys as a list directly.
+
+## Try it
+
+Change the dictionary, add a student, or print only the students who passed (score ≥ 80).
+
+
+
+## Pattern 1: counting things
+
+"How many times does each item appear?" comes up all the time. Start with an empty dictionary and add 1 for each item:
+
+```python
+text = "the cat and the hat and the bat"
+
+counts = {}
+for word in text.split():
+ counts[word] = counts.get(word, 0) + 1
+
+print(counts)
+```
+
+```text
+{'the': 3, 'cat': 1, 'and': 2, 'hat': 1, 'bat': 1}
+```
+
+The trick is `counts.get(word, 0)`. The first time a word appears, there's no entry yet, so `.get` returns `0` and we store `1`.
+
+::: info Later
+The standard library has `collections.Counter`, which does this in one line (see *collections and itertools*). Write the loop yourself first, so you know what `Counter` does for you.
+:::
+
+## Pattern 2: grouping things
+
+A value can be a list, so a dictionary can collect several items under one key:
+
+```python
+words = ["apple", "avocado", "banana", "blueberry", "cherry"]
+
+by_letter = {}
+for word in words:
+ first = word[0]
+ if first not in by_letter:
+ by_letter[first] = []
+ by_letter[first].append(word)
+
+print(by_letter)
+```
+
+```text
+{'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}
+```
+
+The `if ... not in` check creates an empty list the first time each letter is seen. `by_letter.setdefault(first, []).append(word)` does the same thing in one line (but see mistake 4).
+
+## Dictionary or list?
+
+| Question | Use |
+|---|---|
+| Do I find items by **position** or keep them **in sequence**? | list |
+| Do I find items by a **name or ID**? | dict |
+| Do I need to check "is X here?" quickly for many items? | dict (or set) |
+| Does each item have **named fields** (name, age, email)? | dict |
+
+Often you'll use both together, for example a list of dictionaries (a list of students). The *Nested Data* lesson covers that.
+
+## Common mistakes
+
+### 1. Reading a key that doesn't exist
+
+```py
+user = {"name": "Aziza"}
+print(user["email"])
+```
+
+```text
+KeyError: 'email'
+```
+
+**Fix:** check with `"email" in user` first, or use `user.get("email", default)`.
+
+### 2. Expecting `in` to search values
+
+```python
+capitals = {"Uzbekistan": "Tashkent", "Japan": "Tokyo"}
+print("Tokyo" in capitals) # checks KEYS
+print("Tokyo" in capitals.values())
+```
+
+```text
+False
+True
+```
+
+### 3. Changing a dictionary's size while looping over it
+
+```py
+stock = {"apple": 0, "banana": 5, "cherry": 0}
+for item in stock:
+ if stock[item] == 0:
+ del stock[item]
+```
+
+```text
+RuntimeError: dictionary changed size during iteration
+```
+
+**Fix:** loop over a snapshot of the keys, `list(stock)`, so deleting doesn't disturb the loop:
+
+```python
+stock = {"apple": 0, "banana": 5, "cherry": 0}
+for item in list(stock):
+ if stock[item] == 0:
+ del stock[item]
+print(stock)
+```
+
+```text
+{'banana': 5}
+```
+
+*Comprehensions* shows another fix: build a new dictionary with only the items you keep.
+
+### 4. Grouping with `.get()` instead of `.setdefault()`
+
+```python
+words = ["apple", "avocado", "banana"]
+by_letter = {}
+for word in words:
+ by_letter.get(word[0], []).append(word)
+print(by_letter)
+```
+
+```text
+{}
+```
+
+No error, and no data. `.get()` returns a **new** empty list that isn't stored in the dictionary, so every `append` goes into a list that is thrown away. **Fix:** `by_letter.setdefault(word[0], []).append(word)`, which stores the empty list first and returns that stored list.
+
+## Practice
+
+### 1. Phone book
+
+Create a dictionary with three names and phone numbers. Print one person's number, then add a fourth person and print the whole phone book.
+
+::: details Solution
+```python
+phone_book = {
+ "Aziza": "+998 90 123 45 67",
+ "Bekzod": "+998 91 765 43 21",
+ "Dilnoza": "+998 93 111 22 33",
+}
+print(phone_book["Bekzod"])
+
+phone_book["Farrukh"] = "+998 94 555 66 77"
+print(phone_book)
+```
+:::
+
+### 2. Safe lookup
+
+Given the `menu` dictionary and an `item` name, print the item's price, or the text `not on the menu` if the item doesn't exist. Do **not** use `if`. Test with `"tea"` and `"pizza"`.
+
+```py
+menu = {"tea": 1.5, "coffee": 2.0, "samsa": 1.0}
+item = "pizza"
+```
+
+::: details Solution
+```python
+menu = {"tea": 1.5, "coffee": 2.0, "samsa": 1.0}
+item = "pizza"
+
+print(menu.get(item, "not on the menu"))
+```
+:::
+
+### 3. Letter counter
+
+Build a dictionary counting each letter in `text = "Hello World"`. Ignore spaces and treat uppercase and lowercase as the same.
+
+::: details Solution
+```python
+text = "Hello World"
+
+counts = {}
+for char in text.lower():
+ if char == " ":
+ continue
+ counts[char] = counts.get(char, 0) + 1
+
+print(counts)
+```
+
+```text
+{'h': 1, 'e': 1, 'l': 3, 'o': 2, 'w': 1, 'r': 1, 'd': 1}
+```
+:::
+
+### 4. Grade report
+
+Given `scores`, print each student in **alphabetical order** with their score. Then print the class average (rounded to 1 decimal place) and the name of the lowest scorer.
+
+```py
+scores = {"Dilnoza": 85, "Aziza": 92, "Bekzod": 78, "Farrukh": 64}
+```
+
+::: details Solution
+```python
+scores = {"Dilnoza": 85, "Aziza": 92, "Bekzod": 78, "Farrukh": 64}
+
+for name in sorted(scores):
+ print(f"{name}: {scores[name]}")
+
+average = sum(scores.values()) / len(scores)
+lowest = min(scores, key=scores.get)
+
+print(f"Average: {average:.1f}")
+print(f"Lowest: {lowest}")
+```
+:::
+
+### 5. Invert a dictionary
+
+Swap the keys and values of `d = {"a": 1, "b": 2, "c": 1}`. Several keys can share the same value, so each value in the result should map to a **list** of the original keys: `{1: ['a', 'c'], 2: ['b']}`.
+
+::: details Solution
+```python
+d = {"a": 1, "b": 2, "c": 1}
+
+inverted = {}
+for key, value in d.items():
+ if value not in inverted:
+ inverted[value] = []
+ inverted[value].append(key)
+
+print(inverted)
+```
+
+```text
+{1: ['a', 'c'], 2: ['b']}
+```
+
+This is the **grouping** pattern again: here we group keys by their value.
+:::
+
+## Recap
+
+- A dictionary maps unique, immutable **keys** to **values** of any type: `{"key": value}`.
+- `d[key]` reads a value and raises `KeyError` if the key is missing. `d.get(key, default)` never raises.
+- `key in d` checks **keys**, not values.
+- Assigning adds or updates. `del` and `.pop()` remove. `|` merges into a new dictionary.
+- Loop with `.items()` to get keys and values together. Views are live, so loop over `list(d)` if you add or remove keys.
+
+## Further reading
+
+- [Python Tutorial - Dictionaries](https://docs.python.org/3/tutorial/datastructures.html#dictionaries)
+- [Library reference - Mapping types (`dict`)](https://docs.python.org/3/library/stdtypes.html#mapping-types-dict)
+- [Glossary - hashable](https://docs.python.org/3/glossary.html#term-hashable)
diff --git a/docs/lessons/05-collections/05-sets.md b/docs/lessons/05-collections/05-sets.md
new file mode 100644
index 0000000..ae5391a
--- /dev/null
+++ b/docs/lessons/05-collections/05-sets.md
@@ -0,0 +1,449 @@
+---
+title: Sets
+description: "Store unique values with sets: creating sets, adding and removing items, fast membership tests, removing duplicates, and set operations like union, intersection, and difference."
+---
+
+# Sets
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- What a **set** is: an unordered collection of **unique** values
+- How to create sets, including the empty set
+- How to add and remove items safely
+- Why checking `x in some_set` is so fast
+- Set operations: union `|`, intersection `&`, difference `-`, and symmetric difference `^`
+:::
+
+## Why it matters
+
+Many questions are about **uniqueness** and **overlap**: *How many different visitors came today? Which students take both math and physics? Which products are in stock but not on sale?* With lists, these need loops. With **sets**, they're one line, and much faster on large data.
+
+## Creating a set
+
+Use curly braces, or `set()` to convert another collection:
+
+```python
+scores = {90, 85, 100, 90}
+print(scores)
+print(len(scores))
+
+letters = set("banana")
+print(letters)
+```
+
+```text
+{90, 100, 85}
+3
+{'a', 'n', 'b'} # order may differ when you run it
+```
+
+Two things to notice:
+
+1. **Duplicates disappear.** `90` appears twice but is stored once, and `"banana"` has six letters but only three unique ones.
+2. **There's no order.** The numbers didn't come out sorted or in the order you typed them. For strings it's even less predictable: the order of `letters` can change from one run to the next, so your output may not match the line above.
+
+::: warning The empty set
+`{}` creates an empty **dictionary**, not a set. Use `set()` for an empty set:
+
+```python
+empty_set = set()
+empty_dict = {}
+print(type(empty_set), type(empty_dict))
+```
+:::
+
+## Removing duplicates
+
+The quickest way to get unique values is to convert to a set:
+
+```python
+visitors = ["aziza", "bekzod", "aziza", "dilnoza", "bekzod", "aziza"]
+
+unique_visitors = set(visitors)
+print(len(visitors), "visits")
+print(len(unique_visitors), "unique visitors")
+```
+
+```text
+6 visits
+3 unique visitors
+```
+
+If you need a list again, especially a sorted one: `sorted(set(visitors))`.
+
+If you need to keep the **original order**, use `dict.fromkeys()`, since dictionaries remember insertion order:
+
+```python
+visitors = ["aziza", "bekzod", "aziza", "dilnoza", "bekzod", "aziza"]
+print(list(dict.fromkeys(visitors)))
+```
+
+```text
+['aziza', 'bekzod', 'dilnoza']
+```
+
+## Adding and removing
+
+```python
+tags = {"python", "beginner"}
+
+tags.add("loops")
+tags.add("python") # already there: nothing happens
+print(tags)
+
+tags.remove("beginner") # KeyError if missing
+tags.discard("advanced") # no error if missing
+print(tags)
+```
+
+| Method | What it does |
+|---|---|
+| `s.add(x)` | add one item (no effect if it's already there) |
+| `s.update(items)` | add many items |
+| `s.remove(x)` | remove `x`, raise `KeyError` if it's missing |
+| `s.discard(x)` | remove `x` if present, otherwise do nothing |
+| `s.pop()` | remove and return an arbitrary item |
+| `s.clear()` | remove everything |
+
+## No indexing
+
+Sets have no positions, so there's no `s[0]`:
+
+```py
+colors = {"red", "green"}
+print(colors[0])
+```
+
+```text
+TypeError: 'set' object is not subscriptable
+```
+
+You can still loop over a set and use `len()` and `in`. To process items in a predictable order, loop over `sorted(the_set)`.
+
+## Fast membership tests
+
+Checking `x in some_set` is **very fast**, no matter how big the set is. For a list, Python has to look at the items one by one. For a set, it jumps almost straight to the answer, using a technique called *hashing*.
+
+```python
+banned_words = {"spam", "scam", "fake"}
+
+message = "this is not a scam offer"
+for word in message.split():
+ if word in banned_words:
+ print(f"Blocked word found: {word}")
+```
+
+```text
+Blocked word found: scam
+```
+
+### How fast is it?
+
+Time it yourself. This checks 100 times whether a missing ID is in a list and in a set, each with 100,000 items:
+
+```python
+import time
+
+ids_list = list(range(100_000))
+ids_set = set(ids_list)
+
+start = time.perf_counter()
+for _ in range(100):
+ -1 in ids_list
+list_time = time.perf_counter() - start
+
+start = time.perf_counter()
+for _ in range(100):
+ -1 in ids_set
+set_time = time.perf_counter() - start
+
+print(f"list: {list_time:.4f} s")
+print(f"set: {set_time:.6f} s")
+```
+
+```text
+list: 0.1050 s
+set: 0.000009 s
+```
+
+Your times will differ (the browser is slower than a local Python), but the gap is always huge. The list has to compare `-1` with all 100,000 items every time. The set does about the same small amount of work whether it holds 10 items or 10 million.
+
+The gap matters most **inside a loop**. Checking each of 10,000 new orders against a *list* of 10,000 known IDs means up to 10,000 × 10,000 = 100 million comparisons, which is a loop inside a loop. Against a *set*, it's about 10,000 quick lookups. When code feels slow, look for `in` on a list inside a `for` loop.
+
+### What can go in a set?
+
+Items must be **hashable**, which roughly means **immutable**: numbers, strings, booleans, and tuples of those. Lists, dictionaries, and other sets can't be set items:
+
+```py
+pairs = {[1, 2], [3, 4]}
+```
+
+```text
+TypeError: cannot use 'list' as a set element (unhashable type: 'list')
+```
+
+Use tuples instead: `{(1, 2), (3, 4)}`.
+
+## Set operations
+
+This is where sets really shine. Imagine two classes:
+
+```python
+math = {"Aziza", "Bekzod", "Dilnoza", "Farrukh"}
+physics = {"Bekzod", "Farrukh", "Gulnora"}
+```
+
+Bekzod and Farrukh are in both classes. Aziza and Dilnoza take only math, and Gulnora takes only physics.
+
+| Operation | Operator | Method | Meaning |
+|---|---|---|---|
+| Union | `a \| b` | `a.union(b)` | in **either** set |
+| Intersection | `a & b` | `a.intersection(b)` | in **both** sets |
+| Difference | `a - b` | `a.difference(b)` | in `a` but **not** in `b` |
+| Symmetric difference | `a ^ b` | `a.symmetric_difference(b)` | in **exactly one** of them |
+
+```python
+math = {"Aziza", "Bekzod", "Dilnoza", "Farrukh"}
+physics = {"Bekzod", "Farrukh", "Gulnora"}
+
+print("Any class: ", sorted(math | physics))
+print("Both: ", sorted(math & physics))
+print("Only math: ", sorted(math - physics))
+print("Only one: ", sorted(math ^ physics))
+```
+
+```text
+Any class: ['Aziza', 'Bekzod', 'Dilnoza', 'Farrukh', 'Gulnora']
+Both: ['Bekzod', 'Farrukh']
+Only math: ['Aziza', 'Dilnoza']
+Only one: ['Aziza', 'Dilnoza', 'Gulnora']
+```
+
+(`sorted()` just makes the output order predictable.)
+
+### Subsets and overlaps
+
+```python
+required = {"python", "git"}
+skills = {"python", "git", "sql", "docker"}
+
+print(required <= skills) # subset: every required skill is present
+print(required.issubset(skills)) # same thing
+print(skills >= required) # superset
+print(required.isdisjoint({"java"})) # no items in common
+```
+
+```text
+True
+True
+True
+True
+```
+
+### Comparing sets
+
+Two sets are equal if they contain the same items, regardless of order:
+
+```python
+print({1, 2, 3} == {3, 2, 1})
+```
+
+```text
+True
+```
+
+## frozenset
+
+A `frozenset` is an immutable set. It can be used as a dictionary key or as an item in another set. You won't need it often:
+
+```python
+weekend = frozenset({"Sat", "Sun"})
+print("Sun" in weekend)
+```
+
+## Try it
+
+Compare the ingredients you have with two recipes. Add or remove ingredients and see what changes.
+
+
+
+## Common mistakes
+
+### 1. `{}` for an empty set
+
+```py
+items = {}
+items.add("x")
+```
+
+```text
+AttributeError: 'dict' object has no attribute 'add'
+```
+
+`{}` is an empty dictionary. **Fix:** `items = set()`.
+
+### 2. `set("word")` vs `{"word"}`
+
+```python
+print(len(set("hello"))) # the letters h, e, l, o
+print({"hello"}) # one item
+```
+
+```text
+4
+{'hello'}
+```
+
+`set()` takes an iterable and adds **each item**. A string's items are its characters.
+
+### 3. Using an operator with a list
+
+```py
+math = {"Aziza", "Bekzod"}
+print(math | ["Hasan"])
+```
+
+```text
+TypeError: unsupported operand type(s) for |: 'set' and 'list'
+```
+
+The operators need sets on both sides. **Fix:** `math | set(["Hasan"])`, or use the method, which accepts any iterable: `math.union(["Hasan"])`.
+
+### 4. `remove` on a missing item
+
+```py
+s = {"a"}
+s.remove("b")
+```
+
+```text
+KeyError: 'b'
+```
+
+**Fix:** use `discard` when the item might not be there.
+
+## Practice
+
+### 1. Unique letters
+
+How many **different** letters are in `"mississippi"`? Print the count and the letters in alphabetical order.
+
+::: details Solution
+```python
+word = "mississippi"
+unique = set(word)
+print(len(unique), sorted(unique))
+```
+
+```text
+4 ['i', 'm', 'p', 's']
+```
+:::
+
+### 2. Common friends
+
+Aziza's friends are `{"Bobur", "Charos", "Dilshod", "Eldor"}` and Bekzod's are `{"Charos", "Eldor", "Farida"}`. Print their common friends and all friends who are **not** shared.
+
+::: details Solution
+```python
+aziza = {"Bobur", "Charos", "Dilshod", "Eldor"}
+bekzod = {"Charos", "Eldor", "Farida"}
+
+print("Common:", sorted(aziza & bekzod))
+print("Not shared:", sorted(aziza ^ bekzod))
+```
+:::
+
+### 3. Is it a pangram?
+
+A **pangram** uses every letter of the English alphabet at least once. Check whether `"The quick brown fox jumps over the lazy dog"` is a pangram, and print any missing letters for `"Hello world"`.
+
+::: details Solution
+```python
+import string
+
+alphabet = set(string.ascii_lowercase)
+
+for sentence in ["The quick brown fox jumps over the lazy dog", "Hello world"]:
+ missing = alphabet - set(sentence.lower())
+ if not missing:
+ print("Pangram!")
+ else:
+ print("Missing:", "".join(sorted(missing)))
+```
+
+`string.ascii_lowercase` is the text `"abcdefghijklmnopqrstuvwxyz"`. Spaces and punctuation in the sentence don't matter, because we only look at what's missing from the alphabet.
+:::
+
+### 4. New and lost customers
+
+Given customer IDs from two months:
+
+```python
+august = [101, 102, 103, 104, 105, 102, 101]
+september = [102, 104, 106, 107, 104]
+```
+
+Print how many unique customers each month had, who is **new** in September, who **didn't return**, and who bought in **both** months.
+
+::: details Solution
+```python
+august = [101, 102, 103, 104, 105, 102, 101]
+september = [102, 104, 106, 107, 104]
+
+aug = set(august)
+sep = set(september)
+
+print(f"August: {len(aug)} customers, September: {len(sep)} customers")
+print("New:", sorted(sep - aug))
+print("Didn't return:", sorted(aug - sep))
+print("Loyal:", sorted(aug & sep))
+```
+
+```text
+August: 5 customers, September: 4 customers
+New: [106, 107]
+Didn't return: [101, 103, 105]
+Loyal: [102, 104]
+```
+:::
+
+### 5. Duplicate finder
+
+Given `codes = ["A12", "B07", "A12", "C33", "B07", "D90", "A12"]`, print the codes that appear **more than once**, in the order they **first became duplicates**, using sets (not `.count()`).
+
+::: details Solution
+```python
+codes = ["A12", "B07", "A12", "C33", "B07", "D90", "A12"]
+
+seen = set()
+duplicates = []
+
+for code in codes:
+ if code in seen and code not in duplicates:
+ duplicates.append(code)
+ seen.add(code)
+
+print(duplicates)
+```
+
+```text
+['A12', 'B07']
+```
+
+`seen` answers "have I met this before?" instantly. Using `.count()` inside a loop would re-scan the whole list for every item, which is slow for big data.
+:::
+
+## Recap
+
+- A **set** holds unique, hashable items with no order and no indexing: `{"a", "b"}`. Use `set()` for an empty set.
+- `set(items)` removes duplicates. `list(dict.fromkeys(items))` removes them and keeps the order.
+- `add`, `update`, `remove` (error if missing), `discard` (no error), and `clear` change a set.
+- `x in s` is very fast, while `x in a_list` checks every item. Avoid `in` on a big list inside a loop.
+- Operations: `|` union, `&` intersection, `-` difference, `^` symmetric difference, and `<=` subset.
+
+## Further reading
+
+- [Python Tutorial - Sets](https://docs.python.org/3/tutorial/datastructures.html#sets)
+- [Set types - `set`, `frozenset`](https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset)
diff --git a/docs/lessons/05-collections/06-nested-data.md b/docs/lessons/05-collections/06-nested-data.md
new file mode 100644
index 0000000..a25f335
--- /dev/null
+++ b/docs/lessons/05-collections/06-nested-data.md
@@ -0,0 +1,524 @@
+---
+title: Nested Data
+description: "Combine lists, dictionaries, and tuples into realistic data: lists of dictionaries, dictionaries of lists, grids, reading and updating nested values, and avoiding shared-copy bugs."
+---
+
+# Nested Data
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- How to put collections inside collections
+- The most common shapes: **list of dictionaries**, **dictionary of lists**, **dictionary of dictionaries**, and **list of lists**
+- How to read and update values several levels deep
+- How to loop through nested data and summarize it
+- The shallow-copy and `[[0] * 3] * 3` traps
+:::
+
+## Why it matters
+
+Real data is rarely a flat list of numbers. A shop has products, each with a name, price, and tags. A school has classes of students with several grades. Data from websites and APIs (usually JSON) is nested in exactly this way, so once you can navigate nested structures, you can handle almost any data a program receives.
+
+## Shape 1: a list of dictionaries
+
+**Many records with the same fields.** This is the most common shape: think of rows in a table.
+
+```python
+students = [
+ {"name": "Aziza", "age": 20, "city": "Tashkent"},
+ {"name": "Bekzod", "age": 22, "city": "Samarkand"},
+ {"name": "Dilnoza", "age": 19, "city": "Tashkent"},
+]
+
+print(students[1]) # one whole record
+print(students[1]["name"]) # one field of one record
+
+for student in students: # one dictionary at a time
+ print(f"{student['name']:<8} {student['city']}")
+```
+
+```text
+{'name': 'Bekzod', 'age': 22, 'city': 'Samarkand'}
+Bekzod
+Aziza Tashkent
+Bekzod Samarkand
+Dilnoza Tashkent
+```
+
+Read `students[1]["name"]` **left to right**: take `students`, get item `1` (a dictionary), then get its `"name"`.
+
+Sorting a list of dictionaries needs a key that picks the field:
+
+```python
+students = [
+ {"name": "Aziza", "age": 20},
+ {"name": "Bekzod", "age": 22},
+ {"name": "Dilnoza", "age": 19},
+]
+
+for s in sorted(students, key=lambda s: s["age"]):
+ print(s["name"], s["age"])
+```
+
+```text
+Dilnoza 19
+Aziza 20
+Bekzod 22
+```
+
+`lambda s: s["age"]` is a tiny function written inline: "given a student `s`, return `s["age"]`". `sorted()` calls it on each dictionary and sorts by the ages it gets back. *Lambdas and Higher-Order Functions* covers `lambda` properly.
+
+## Shape 2: a dictionary of lists
+
+**Several items grouped under each key.**
+
+```python
+grades = {
+ "Aziza": [90, 85, 97],
+ "Bekzod": [72, 64, 80],
+}
+
+grades["Aziza"].append(88) # add a grade for Aziza
+grades["Dilnoza"] = [79] # add a new student
+
+for name, scores in grades.items():
+ average = sum(scores) / len(scores)
+ print(f"{name}: {scores} → {average:.1f}")
+```
+
+```text
+Aziza: [90, 85, 97, 88] → 90.0
+Bekzod: [72, 64, 80] → 72.0
+Dilnoza: [79] → 79.0
+```
+
+To build this shape from flat data, use the grouping pattern from *Dictionaries*:
+
+```python
+orders = [("Aziza", "tea"), ("Bekzod", "coffee"), ("Aziza", "samsa")]
+
+by_customer = {}
+for customer, item in orders:
+ by_customer.setdefault(customer, []).append(item)
+
+print(by_customer)
+```
+
+```text
+{'Aziza': ['tea', 'samsa'], 'Bekzod': ['coffee']}
+```
+
+## Shape 3: a dictionary of dictionaries
+
+**Records you look up by a unique ID.**
+
+```python
+products = {
+ "P001": {"name": "Notebook", "price": 15000, "stock": 40},
+ "P002": {"name": "Pen", "price": 3000, "stock": 0},
+ "P003": {"name": "Backpack", "price": 180000, "stock": 5},
+}
+
+print(products["P003"]["price"])
+
+products["P002"]["stock"] += 25 # update one field
+products["P004"] = {"name": "Ruler", "price": 5000, "stock": 12}
+
+for code, info in products.items():
+ status = "in stock" if info["stock"] > 0 else "SOLD OUT"
+ print(f"{code} {info['name']:<9} {info['price']:>8,} {status}")
+```
+
+```text
+180000
+P001 Notebook 15,000 in stock
+P002 Pen 3,000 in stock
+P003 Backpack 180,000 in stock
+P004 Ruler 5,000 in stock
+```
+
+Unlike a list of dictionaries, finding a record by ID needs no loop.
+
+## Shape 4: a list of lists (a grid)
+
+{.lesson-diagram width=1536 height=1024 loading=lazy}
+
+**Rows and columns**: a game board, a seating chart, or a table of numbers.
+
+```python
+board = [
+ ["X", "O", "X"],
+ [" ", "X", "O"],
+ ["O", " ", "X"],
+]
+
+print(board[0][2]) # row 0, column 2
+
+board[1][0] = "O" # place a mark
+
+for row in board:
+ print(" | ".join(row))
+```
+
+```text
+X
+X | O | X
+O | X | O
+O | | X
+```
+
+`board[row][col]`: the first index picks the row, and the second picks the item in that row.
+
+Nested loops visit every cell:
+
+```python
+matrix = [
+ [1, 2, 3],
+ [4, 5, 6],
+]
+
+total = 0
+for row in matrix:
+ for value in row:
+ total += value
+
+print(total)
+```
+
+```text
+21
+```
+
+## Going deeper
+
+Structures can nest as deep as needed. This looks like typical data from a web API:
+
+```python
+order = {
+ "id": 5012,
+ "customer": {"name": "Aziza", "phone": "+998901234567"},
+ "items": [
+ {"product": "Tea", "qty": 2, "price": 15000},
+ {"product": "Samsa", "qty": 4, "price": 8000},
+ ],
+ "delivery": {"address": {"city": "Tashkent", "street": "Amir Temur 1"}},
+}
+
+print(order["customer"]["name"])
+print(order["items"][1]["product"])
+print(order["delivery"]["address"]["city"])
+
+total = 0
+for item in order["items"]:
+ total += item["qty"] * item["price"]
+print(f"Order total: {total:,} som")
+```
+
+```text
+Aziza
+Samsa
+Tashkent
+Order total: 62,000 som
+```
+
+::: tip Work out the path step by step
+Check the type at each level: `order` is a dict → `order["items"]` a list → `order["items"][1]` a dict → `["product"]` a string.
+:::
+
+### Missing keys deep inside
+
+Chained `.get()` calls avoid a `KeyError` when parts may be missing. Give each level an empty dictionary as the default:
+
+```python
+order = {"id": 5013, "customer": {"name": "Bekzod"}}
+
+city = order.get("delivery", {}).get("address", {}).get("city", "unknown")
+print(city)
+```
+
+```text
+unknown
+```
+
+## Printing nested data nicely
+
+`print()` puts everything on one line. The `pprint` module ("pretty print") spreads it out:
+
+```python
+from pprint import pprint
+
+data = {"name": "Aziza", "scores": [90, 85, 97], "address": {"city": "Tashkent", "zip": "100000"}}
+pprint(data, width=40)
+```
+
+```text
+{'address': {'city': 'Tashkent',
+ 'zip': '100000'},
+ 'name': 'Aziza',
+ 'scores': [90, 85, 97]}
+```
+
+## The copying trap
+
+`.copy()` makes a **shallow** copy: the outer container is new, but the inner lists and dictionaries are still **shared**:
+
+```python
+original = {"name": "Aziza", "scores": [90, 85]}
+shallow = original.copy()
+
+shallow["name"] = "Changed" # replacing a value: only the copy changes
+shallow["scores"].append(100) # changing a shared inner list: both see it
+
+print(original)
+print(shallow)
+```
+
+```text
+{'name': 'Aziza', 'scores': [90, 85, 100]}
+{'name': 'Changed', 'scores': [90, 85, 100]}
+```
+
+For a completely independent copy, `import copy` and use `copy.deepcopy(original)`. It copies the inner lists and dictionaries too, at every level.
+
+## Try it
+
+Explore the nested order data: add an item, change a quantity, or print the most expensive line.
+
+
+
+## Common mistakes
+
+### 1. Wrong type at some level
+
+```py
+students = [{"name": "Aziza"}, {"name": "Bekzod"}]
+print(students["name"])
+```
+
+```text
+TypeError: list indices must be integers or slices, not str
+```
+
+`students` is a **list**, so it needs a number first: `students[0]["name"]`. Print `type()` one level at a time to find where the path goes wrong.
+
+### 2. Building a grid with `*`
+
+```python
+grid = [[0] * 3] * 3 # looks like 3 separate rows...
+grid[0][0] = 1
+print(grid)
+```
+
+```text
+[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
+```
+
+`* 3` repeated the **same** inner list three times. **Fix:** create a new row each time:
+
+```python
+grid = [[0] * 3 for _ in range(3)]
+grid[0][0] = 1
+print(grid)
+```
+
+```text
+[[1, 0, 0], [0, 0, 0], [0, 0, 0]]
+```
+
+### 3. Copying a grid with `.copy()`
+
+```python
+grid = [[0, 0], [0, 0]]
+backup = grid.copy()
+grid[0][0] = 9
+print(backup)
+```
+
+```text
+[[9, 0], [0, 0]]
+```
+
+The "backup" changed too. `.copy()` copied the outer list, but both lists hold the **same** row lists. **Fix:** `copy.deepcopy(grid)`, or copy each row: `[row.copy() for row in grid]`.
+
+## Practice
+
+### 1. Book shelf
+
+Given
+
+```python
+books = [
+ {"title": "Python Basics", "year": 2021, "pages": 320},
+ {"title": "Data Science Intro", "year": 2019, "pages": 450},
+ {"title": "Web with Python", "year": 2023, "pages": 280},
+]
+```
+
+print the title of the second book, then the total number of pages of all books.
+
+::: details Solution
+```python
+books = [
+ {"title": "Python Basics", "year": 2021, "pages": 320},
+ {"title": "Data Science Intro", "year": 2019, "pages": 450},
+ {"title": "Web with Python", "year": 2023, "pages": 280},
+]
+
+print(books[1]["title"])
+
+total_pages = 0
+for book in books:
+ total_pages += book["pages"]
+print(total_pages)
+```
+:::
+
+### 2. Class averages
+
+For `classes = {"9A": [4, 5, 3, 5], "9B": [5, 5, 4], "9C": [3, 4, 4, 2, 5]}`, print each class with its average grade (2 decimals).
+
+::: details Solution
+```python
+classes = {"9A": [4, 5, 3, 5], "9B": [5, 5, 4], "9C": [3, 4, 4, 2, 5]}
+
+for name, marks in classes.items():
+ print(f"{name}: {sum(marks) / len(marks):.2f}")
+```
+:::
+
+### 3. Tic-tac-toe winner
+
+Check every **row** and **column** of this `board`. Print the winning symbol if one holds three identical marks that aren't `" "`, otherwise `No winner yet`.
+
+```python
+board = [
+ ["X", "O", "O"],
+ ["X", "O", " "],
+ ["X", " ", "O"],
+]
+```
+
+::: details Solution
+```python
+board = [
+ ["X", "O", "O"],
+ ["X", "O", " "],
+ ["X", " ", "O"],
+]
+
+winner = None
+
+for i in range(3):
+ row = board[i]
+ column = [board[r][i] for r in range(3)]
+ for line in (row, column):
+ if line[0] != " " and line[0] == line[1] == line[2]:
+ winner = line[0]
+
+print(f"Winner: {winner}" if winner else "No winner yet")
+```
+
+```text
+Winner: X
+```
+:::
+
+### 4. Inventory report
+
+Using this dictionary of dictionaries, print the products that need restocking (stock below `min_stock`), and the total value of all stock (price × stock).
+
+```python
+inventory = {
+ "tea": {"price": 15000, "stock": 12, "min_stock": 20},
+ "sugar": {"price": 9000, "stock": 50, "min_stock": 30},
+ "coffee": {"price": 45000, "stock": 4, "min_stock": 10},
+}
+```
+
+::: details Solution
+```python
+inventory = {
+ "tea": {"price": 15000, "stock": 12, "min_stock": 20},
+ "sugar": {"price": 9000, "stock": 50, "min_stock": 30},
+ "coffee": {"price": 45000, "stock": 4, "min_stock": 10},
+}
+
+total_value = 0
+for product, info in inventory.items():
+ total_value += info["price"] * info["stock"]
+ if info["stock"] < info["min_stock"]:
+ need = info["min_stock"] - info["stock"]
+ print(f"Restock {product}: order at least {need}")
+
+print(f"Total stock value: {total_value:,} som")
+```
+
+```text
+Restock tea: order at least 8
+Restock coffee: order at least 6
+Total stock value: 810,000 som
+```
+:::
+
+### 5. Group and summarize
+
+Turn these sales into a dictionary mapping each **city** to a dictionary with its **number of sales** and **total amount**. Print the cities by total, highest first.
+
+```python
+sales = [
+ {"city": "Tashkent", "amount": 120000},
+ {"city": "Samarkand", "amount": 80000},
+ {"city": "Tashkent", "amount": 45000},
+ {"city": "Bukhara", "amount": 150000},
+ {"city": "Samarkand", "amount": 30000},
+]
+```
+
+Expected result:
+
+```text
+Tashkent: 2 sales, 165,000 som
+Bukhara: 1 sales, 150,000 som
+Samarkand: 2 sales, 110,000 som
+```
+
+::: details Solution
+```python
+sales = [
+ {"city": "Tashkent", "amount": 120000},
+ {"city": "Samarkand", "amount": 80000},
+ {"city": "Tashkent", "amount": 45000},
+ {"city": "Bukhara", "amount": 150000},
+ {"city": "Samarkand", "amount": 30000},
+]
+
+summary = {}
+for sale in sales:
+ city = sale["city"]
+ if city not in summary:
+ summary[city] = {"count": 0, "total": 0}
+ summary[city]["count"] += 1
+ summary[city]["total"] += sale["amount"]
+
+ranked = sorted(summary.items(), key=lambda pair: pair[1]["total"], reverse=True)
+
+for city, stats in ranked:
+ print(f"{city}: {stats['count']} sales, {stats['total']:,} som")
+```
+
+`summary.items()` gives `(city, stats)` pairs, so the `lambda` key reaches into the inner dictionary with `pair[1]["total"]`.
+:::
+
+## Recap
+
+- Collections can contain other collections. Read access paths **left to right**: `data["items"][0]["price"]`.
+- **List of dicts** for records with the same fields, **dict of lists** for groups, **dict of dicts** for records by ID, and **list of lists** for grids.
+- Loop one level at a time, and use nested loops for grids. Chained `.get(key, {})` handles optional parts, and `pprint` displays deep data.
+- Build grids with `[[0] * cols for _ in range(rows)]`, not `[[0] * cols] * rows`.
+- `.copy()` is shallow, for dicts and grids alike. Use `copy.deepcopy()` for fully independent nested copies.
+
+## Further reading
+
+- [Python Tutorial - Data structures](https://docs.python.org/3/tutorial/datastructures.html)
+- [`pprint` - data pretty printer](https://docs.python.org/3/library/pprint.html)
+- [`copy` - shallow and deep copy](https://docs.python.org/3/library/copy.html)
diff --git a/docs/lessons/05-collections/07-comprehensions.md b/docs/lessons/05-collections/07-comprehensions.md
new file mode 100644
index 0000000..2ffd9bf
--- /dev/null
+++ b/docs/lessons/05-collections/07-comprehensions.md
@@ -0,0 +1,426 @@
+---
+title: Comprehensions
+description: "Build lists, dictionaries, and sets in one readable line with comprehensions: transforming, filtering, conditional values, nested loops, generator expressions, and when a regular loop is better."
+---
+
+# Comprehensions
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- How to turn a "build a list in a loop" into a one-line **list comprehension**
+- How to **filter** with `if` and choose values with `if … else`
+- **Dictionary** and **set** comprehensions, and comprehensions with two `for` clauses
+- **Generator expressions** with `sum()`, `any()`, and `all()`, and why they work only once
+- When a normal loop is the better choice, and how list, tuple, dict, and set compare
+:::
+
+## Why it matters
+
+Much everyday code has one shape: *take a collection, transform or filter each item, collect the results.* Comprehensions express that shape directly, in less code than a loop, and they're everywhere in real Python.
+
+## From loop to comprehension
+
+Here's the familiar pattern:
+
+```python
+numbers = [1, 2, 3, 4, 5]
+
+squares = []
+for n in numbers:
+ squares.append(n * n)
+
+print(squares)
+```
+
+The same thing as a **list comprehension**:
+
+```python
+numbers = [1, 2, 3, 4, 5]
+
+squares = [n * n for n in numbers]
+
+print(squares)
+```
+
+```text
+[1, 4, 9, 16, 25]
+```
+
+Read it as: **"`n * n`, for each `n` in `numbers`"**. The general shape is `[expression for item in iterable]`: first what to collect, then where the items come from.
+
+The expression can be anything:
+
+```python
+names = ["aziza", "bekzod", "dilnoza"]
+prices = [12000, 4500, 30000]
+
+print([name.title() for name in names])
+print([len(name) for name in names])
+print([f"{p:,} som" for p in prices])
+```
+
+```text
+['Aziza', 'Bekzod', 'Dilnoza']
+[5, 6, 7]
+['12,000 som', '4,500 som', '30,000 som']
+```
+
+### The loop variable stays inside
+
+A comprehension's loop variable doesn't leak out or overwrite a variable of the same name. A `for` loop's does:
+
+```python
+x = "outer"
+squares = [x * x for x in range(3)]
+print(x)
+
+for x in range(3):
+ pass
+print(x)
+```
+
+```text
+outer
+2
+```
+
+## Filtering with `if`
+
+Add `if condition` at the **end** to keep only some items. This replaces the "filter" loop from *Lists*: an empty list, a `for`, an `if`, and `.append()`.
+
+```python
+scores = [72, 95, 58, 88, 64, 91]
+
+high = [s for s in scores if s >= 85]
+curved = [s + 5 for s in scores if s < 60] # transform and filter
+
+print(high)
+print(curved)
+```
+
+```text
+[95, 88, 91]
+[63]
+```
+
+## Choosing a value with `if … else`
+
+To give **every item** a value that depends on a condition, put a conditional expression (from *if, elif, and else*) at the **front**:
+
+```python
+scores = [72, 95, 58, 88]
+
+results = ["pass" if s >= 60 else "fail" for s in scores]
+print(results)
+```
+
+```text
+['pass', 'pass', 'fail', 'pass']
+```
+
+::: warning Where does the `if` go?
+- `[x for x in items if condition]`: the `if` at the **end** **filters**, so the result may be shorter.
+- `[a if condition else b for x in items]`: the `if … else` at the **front** **chooses a value**, so the result has the same length.
+
+An `if` at the end can't have an `else`.
+:::
+
+## Dictionary comprehensions
+
+Use curly braces with `key: value`. They're great for transforming or filtering an existing dictionary via `.items()`:
+
+```python
+prices = {"tea": 15000, "coffee": 45000, "juice": 12000}
+
+with_vat = {item: round(price * 1.12) for item, price in prices.items()}
+cheap = {item: price for item, price in prices.items() if price < 20000}
+
+print(with_vat)
+print(cheap)
+```
+
+```text
+{'tea': 16800, 'coffee': 50400, 'juice': 13440}
+{'tea': 15000, 'juice': 12000}
+```
+
+To pair two lists with no change to the values, `dict(zip(keys, values))` from *Dictionaries* is simpler than a comprehension.
+
+## Set comprehensions
+
+Curly braces **without** a colon build a set, so duplicates are removed:
+
+```python
+emails = ["ali@mail.uz", "vali@gmail.com", "gani@mail.uz", "sami@yahoo.com"]
+
+domains = {email.split("@")[1] for email in emails}
+print(sorted(domains))
+```
+
+```text
+['gmail.com', 'mail.uz', 'yahoo.com']
+```
+
+## Two `for` clauses
+
+A comprehension can contain several `for` clauses. They run in the **same order** as nested loops written out:
+
+```python
+pairs = [(x, y) for x in range(1, 3) for y in "ab"]
+print(pairs)
+```
+
+```text
+[(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]
+```
+
+That's the same as `for x in range(1, 3):` with `for y in "ab":` nested inside it.
+
+A common use is **flattening** a list of lists:
+
+```python
+matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
+
+flat = [value for row in matrix for value in row]
+print(flat)
+```
+
+```text
+[1, 2, 3, 4, 5, 6, 7, 8, 9]
+```
+
+A comprehension can also build nested lists, which is the safe way to create a grid: `[[0] * 4 for _ in range(3)]` (see *Nested Data*).
+
+## Generator expressions
+
+Use **parentheses** instead of square brackets, and you get a *generator expression*. It produces items one at a time, **without building a list**. That's ideal when the values go straight into a function like `sum()`, `max()`, `any()`, `all()`, or `"".join()`:
+
+```python
+prices = [12000, 4500, 30000, 8000]
+
+total_with_vat = sum(p * 1.12 for p in prices)
+has_expensive = any(p > 25000 for p in prices)
+all_affordable = all(p < 50000 for p in prices)
+
+print(round(total_with_vat))
+print(has_expensive, all_affordable)
+print(", ".join(str(p) for p in prices))
+```
+
+```text
+61040
+True True
+12000, 4500, 30000, 8000
+```
+
+`any()` is the one-line version of the flag-and-`break` search from *Common Loop Patterns*.
+
+When the generator is the only argument, you don't need extra parentheses. And there's no tuple comprehension: `(x for x in items)` is a generator, so write `tuple(x for x in items)` for a tuple.
+
+## When not to use a comprehension
+
+Comprehensions are for **building a collection**. Prefer a regular loop when:
+
+1. **It gets hard to read.**
+
+```python
+data = [[1, -2], [3, 4], [-5, 6]]
+
+# Bad: too clever
+result = [x * 2 if x > 0 else 0 for row in data for x in row if x != 4]
+
+# Good: clearer
+result = []
+for row in data:
+ for x in row:
+ if x == 4:
+ continue
+ result.append(x * 2 if x > 0 else 0)
+print(result)
+```
+
+2. **You only want side effects.** `[print(x) for x in items]` builds a useless list of `None`s.
+3. **You need `break`, several statements, or error handling** inside the loop.
+
+If a comprehension doesn't fit on one or two lines, use a loop.
+
+## Choosing a collection
+
+All four built-in collections, side by side:
+
+| | list | tuple | dict | set |
+|---|---|---|---|---|
+| Written as | `[1, 2]` | `(1, 2)` | `{"a": 1}` | `{1, 2}` |
+| Keeps order? | yes | yes | yes (insertion order) | no |
+| Can change? | yes | no | yes | yes |
+| Duplicates? | allowed | allowed | keys are unique | no |
+| Find items by | position | position | key | `in` only |
+
+Of the four, only a tuple of immutable values can be a dict key or set item.
+
+## Try it
+
+Try filtering by a different price, or build a different dictionary.
+
+
+
+## Common mistakes
+
+### 1. `else` in a filter
+
+```py
+evens = [n for n in range(10) if n % 2 == 0 else 0]
+```
+
+```text
+SyntaxError: invalid syntax
+```
+
+If you want a value for every item, move the condition to the front: `[n if n % 2 == 0 else 0 for n in range(10)]`.
+
+### 2. Wrong order of nested `for` clauses
+
+```py
+matrix = [[1, 2], [3, 4]]
+flat = [value for value in row for row in matrix]
+```
+
+```text
+NameError: name 'row' is not defined. Did you mean: 'pow'?
+```
+
+`row` is used before the clause that defines it. **Fix:** write the `for` clauses in the same order as nested loops, outer first: `[value for row in matrix for value in row]`.
+
+### 3. Using a generator expression twice
+
+```python
+prices = [12000, 4500, 30000, 8000]
+cheap = (p for p in prices if p < 10000)
+print(sum(cheap))
+print(sum(cheap))
+```
+
+```text
+12500
+0
+```
+
+A generator produces its items **once**. The first `sum()` used them all up, so the second sees nothing, and there's no error to warn you. **Fix:** use a list (`[...]`) if you need the values more than once.
+
+## Practice
+
+### 1. Celsius to Fahrenheit
+
+Convert `celsius = [0, 12.5, 25, 37, 100]` to a list of Fahrenheit values (`c * 9 / 5 + 32`) with one comprehension.
+
+::: details Solution
+```python
+celsius = [0, 12.5, 25, 37, 100]
+fahrenheit = [c * 9 / 5 + 32 for c in celsius]
+print(fahrenheit)
+```
+
+```text
+[32.0, 54.5, 77.0, 98.6, 212.0]
+```
+:::
+
+### 2. Only the vowels' positions
+
+For `word = "education"`, build a list of the **positions** of all vowels, using `enumerate()` inside a comprehension.
+
+::: details Solution
+```python
+word = "education"
+positions = [i for i, letter in enumerate(word) if letter in "aeiou"]
+print(positions)
+```
+
+```text
+[0, 2, 4, 6, 7]
+```
+:::
+
+### 3. Word lengths dictionary
+
+For `sentence = "comprehensions make python code short and clear"`, build a dictionary mapping each word to its length, but **only for words longer than 4 letters**.
+
+::: details Solution
+```python
+sentence = "comprehensions make python code short and clear"
+lengths = {word: len(word) for word in sentence.split() if len(word) > 4}
+print(lengths)
+```
+
+```text
+{'comprehensions': 14, 'python': 6, 'short': 5, 'clear': 5}
+```
+:::
+
+### 4. Rewrite the loop
+
+Rewrite this code as a single comprehension:
+
+```python
+result = []
+for n in range(1, 21):
+ if n % 3 == 0:
+ result.append(n * n)
+ else:
+ result.append(-n)
+```
+
+Then write a second comprehension that keeps **only** the squares of multiples of 3.
+
+::: details Solution
+```python
+result = [n * n if n % 3 == 0 else -n for n in range(1, 21)]
+squares_of_threes = [n * n for n in range(1, 21) if n % 3 == 0]
+
+print(result)
+print(squares_of_threes)
+```
+
+Choosing a value: condition at the front. Filtering: at the end.
+:::
+
+### 5. Transpose a matrix
+
+**Transposing** a matrix turns rows into columns. Transpose `matrix = [[1, 2, 3], [4, 5, 6]]` into `[[1, 4], [2, 5], [3, 6]]` using a nested list comprehension. Then do the same with `zip()`.
+
+::: details Solution
+```python
+matrix = [[1, 2, 3], [4, 5, 6]]
+
+rows = len(matrix)
+cols = len(matrix[0])
+
+transposed = [[matrix[r][c] for r in range(rows)] for c in range(cols)]
+print(transposed)
+
+with_zip = [list(column) for column in zip(*matrix)]
+print(with_zip)
+```
+
+```text
+[[1, 4], [2, 5], [3, 6]]
+[[1, 4], [2, 5], [3, 6]]
+```
+
+`zip(*matrix)` passes the rows as separate arguments, so it pairs up the items at each position: the columns.
+:::
+
+## Recap
+
+- `[expr for item in items]` builds a list, `{k: v for …}` a dictionary, and `{expr for …}` a set.
+- An `if` at the **end** filters. An `if … else` at the **front** chooses a value for every item.
+- Several `for` clauses run like nested loops, outer first: `[x for row in grid for x in row]`.
+- Generator expressions `(expr for …)` feed `sum`, `any`, `all`, and `join` without building a list, but work only once.
+- Use a regular loop when a comprehension gets hard to read, or when you need side effects, `break`, or several statements.
+
+## Further reading
+
+- [Python Tutorial - List comprehensions](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions)
+- [Python Tutorial - Nested list comprehensions](https://docs.python.org/3/tutorial/datastructures.html#nested-list-comprehensions)
+- [Generator expressions](https://docs.python.org/3/reference/expressions.html#generator-expressions)
diff --git a/docs/lessons/06-functions/01-defining-functions.md b/docs/lessons/06-functions/01-defining-functions.md
new file mode 100644
index 0000000..72937bd
--- /dev/null
+++ b/docs/lessons/06-functions/01-defining-functions.md
@@ -0,0 +1,451 @@
+---
+title: Defining Functions
+description: "Create your own functions with def: naming them, calling them, passing values in with parameters, documenting them with docstrings, and understanding how Python runs them."
+---
+
+# Defining Functions
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- Why functions make programs shorter, clearer, and easier to fix
+- How to define a function with `def` and call it
+- How to give a function input with **parameters**
+- How to document a function with a **docstring**
+- How Python moves through your code when a function is called
+:::
+
+## Why it matters
+
+You've been **using** functions since your first lesson: `print()`, `len()`, `input()`, `sorted()`. Each one hides a chunk of work behind a simple name. Now you'll write your own.
+
+Without functions, programs repeat themselves. If the same ten lines appear in five places and there's a bug, you have to find and fix it five times. With a function, you write the code **once**, give it a name, and use it wherever you need it.
+
+## Your first function
+
+```python
+def greet():
+ print("Hello!")
+ print("Welcome to the course.")
+
+greet()
+greet()
+```
+
+```text
+Hello!
+Welcome to the course.
+Hello!
+Welcome to the course.
+```
+
+There are two separate steps:
+
+1. **Defining** with `def` teaches Python a new command. Nothing is printed yet.
+2. **Calling** with `greet()` runs the code inside. You can call it as many times as you like.
+
+The structure:
+
+```text
+def function_name():
+ body (indented)
+```
+
+- `def` is short for *define*.
+- The name follows the same rules as variable names. Use `snake_case`, and usually a **verb**, because functions *do* things: `greet`, `print_receipt`, `calculate_total`.
+- The parentheses `()` and the colon `:` are required.
+- The body is indented, just like an `if` or a loop.
+
+## Parameters: giving a function input
+
+A function becomes much more useful when it can work with different values. **Parameters** are variables listed in the parentheses. They receive the values you pass when calling:
+
+```python
+def greet(name):
+ print(f"Hello, {name}!")
+
+greet("Aziza")
+greet("Bekzod")
+```
+
+```text
+Hello, Aziza!
+Hello, Bekzod!
+```
+
+When you call `greet("Aziza")`, Python sets `name = "Aziza"` and then runs the body.
+
+- A **parameter** is the name in the definition: `name`.
+- An **argument** is the value in the call: `"Aziza"`.
+
+A function can take several parameters, separated by commas. Arguments are matched **in order**:
+
+```python
+def print_receipt_line(item, quantity, price):
+ total = quantity * price
+ print(f"{item:<10} {quantity} x {price:>6,} = {total:>8,}")
+
+print_receipt_line("Tea", 2, 15000)
+print_receipt_line("Samsa", 4, 8000)
+```
+
+```text
+Tea 2 x 15,000 = 30,000
+Samsa 4 x 8,000 = 32,000
+```
+
+The next lesson, *Parameters and Arguments*, covers default values, keyword arguments, and more.
+
+## Documenting with docstrings
+
+A **docstring** is a string written as the first line of the function body. It describes what the function does:
+
+```python
+def print_banner(title):
+ """Print the title framed by a line of = signs."""
+ line = "=" * (len(title) + 4)
+ print(line)
+ print(f" {title}")
+ print(line)
+
+print_banner("Monthly Report")
+help(print_banner)
+```
+
+```text
+==================
+ Monthly Report
+==================
+Help on function print_banner in module __main__:
+
+print_banner(title)
+ Print the title framed by a line of = signs.
+
+```
+
+Python stores the docstring, so `help()` and code editors can show it. Write docstrings as a short command ("Print…", "Return…"). For larger functions, add details on the following lines.
+
+## How Python runs a function call
+
+When Python reaches a function call, it **jumps** into the function, runs the body, and then **returns** to where it left off:
+
+```python
+def show_step(number):
+ print(f" inside the function: step {number}")
+
+print("1. before")
+show_step(2)
+print("3. after")
+```
+
+```text
+1. before
+ inside the function: step 2
+3. after
+```
+
+### Define before you call
+
+Python reads your file from top to bottom. A function has to be **defined before** the line that calls it runs:
+
+```py
+say_hi()
+
+def say_hi():
+ print("Hi")
+```
+
+```text
+NameError: name 'say_hi' is not defined
+```
+
+A common layout is: imports at the top, then function definitions, then the code that uses them at the bottom.
+
+However, a function body **can** mention another function that's defined later, as long as that function exists by the time the call actually runs:
+
+```python
+def main():
+ print_header() # fine: called only when main() runs
+ print("Body text")
+
+def print_header():
+ print("== Header ==")
+
+main()
+```
+
+```text
+== Header ==
+Body text
+```
+
+## Functions calling functions
+
+Big tasks become manageable when you split them into small functions, each doing one job:
+
+```python
+def print_line():
+ print("-" * 30)
+
+def print_title(text):
+ print_line()
+ print(text.center(30))
+ print_line()
+
+def print_menu():
+ print_title("CAFE MENU")
+ print("Tea ................ 15,000")
+ print("Coffee ............. 45,000")
+ print_line()
+
+print_menu()
+```
+
+```text
+------------------------------
+ CAFE MENU
+------------------------------
+Tea ................ 15,000
+Coffee ............. 45,000
+------------------------------
+```
+
+Changing the line style now means editing **one** function.
+
+## An empty function body
+
+Just like `if`, a function body can't be empty. Use `pass` while you're still planning:
+
+```python
+def send_report():
+ pass # TODO: write this later
+
+send_report() # runs, does nothing
+```
+
+## Functions are values
+
+A function's name refers to a **function object**, just as a variable name refers to a number. Without parentheses, you're talking **about** the function. With parentheses, you **call** it:
+
+```python
+def greet():
+ print("Hello!")
+
+print(greet) # the function itself
+greet() # calling it
+```
+
+```text
+
+Hello!
+```
+
+You used this idea when passing `key=str.lower` to `sorted()`. The *Lambdas and Higher-Order Functions* lesson goes further.
+
+The functions in this lesson **print** their results. Often you want a function to **give back** a value that other code can use, the way `len()` does. That's what `return` does, in *Return Values*.
+
+## Try it
+
+Write a function that prints a box around any text. Try calling it with different words, then add a parameter for the border character.
+
+
+
+## Common mistakes
+
+### 1. Forgetting the parentheses when calling
+
+```python
+def greet():
+ print("Hello!")
+
+greet # does nothing: just refers to the function
+```
+
+The program prints nothing and raises no error, which is what makes this mistake hard to spot. **Fix:** `greet()`.
+
+### 2. Wrong number of arguments
+
+```py
+def greet(name):
+ print(f"Hello, {name}!")
+
+greet()
+```
+
+```text
+TypeError: greet() missing 1 required positional argument: 'name'
+```
+
+```py
+def greet(name):
+ print(f"Hello, {name}!")
+
+greet("Aziza", "Bekzod")
+```
+
+```text
+TypeError: greet() takes 1 positional argument but 2 were given
+```
+
+Pass exactly one argument for each parameter. (Default values, in the next lesson, make some of them optional.)
+
+### 3. Missing colon or indentation
+
+```py
+def greet(name)
+ print(f"Hello, {name}!")
+```
+
+```text
+SyntaxError: expected ':'
+```
+
+```py
+def greet(name):
+print(f"Hello, {name}!")
+```
+
+```text
+IndentationError: expected an indented block after function definition on line 1
+```
+
+**Fix:** end the `def` line with `:` and indent the body by 4 spaces, exactly as with `if` and loops.
+
+## Practice
+
+### 1. Birthday song
+
+Write `sing_birthday(name)` that prints a short birthday song with the name, and call it for two people.
+
+::: details Solution
+```python
+def sing_birthday(name):
+ print("Happy birthday to you,")
+ print("Happy birthday to you,")
+ print(f"Happy birthday, dear {name},")
+ print("Happy birthday to you!")
+ print()
+
+sing_birthday("Aziza")
+sing_birthday("Bekzod")
+```
+:::
+
+### 2. Square of stars
+
+Write `draw_square(size)` that prints a filled square of `*` characters, `size` stars wide and `size` rows tall. Call it with `3` and `5`.
+
+::: details Solution
+```python
+def draw_square(size):
+ for _ in range(size):
+ print("* " * size)
+
+draw_square(3)
+print()
+draw_square(5)
+```
+:::
+
+### 3. Unit conversion table
+
+Write `print_conversion(km)` that prints a line like `5 km = 3.11 miles`. Then use a loop to call it for 1, 5, 10, 21.1, and 42.2 km.
+
+::: details Solution
+```python
+def print_conversion(km):
+ """Print a distance in kilometers and miles."""
+ miles = km * 0.621371
+ print(f"{km:>5} km = {miles:6.2f} miles")
+
+for distance in [1, 5, 10, 21.1, 42.2]:
+ print_conversion(distance)
+```
+:::
+
+### 4. Order of calls
+
+Without running it, write down the exact output. Then run it to check.
+
+```python
+def a():
+ print("A start")
+ b()
+ print("A end")
+
+def b():
+ print("B")
+
+print("main start")
+a()
+b()
+print("main end")
+```
+
+::: details Solution
+```text
+main start
+A start
+B
+A end
+B
+main end
+```
+
+When `a()` calls `b()`, Python finishes all of `b` and then returns to the next line inside `a`.
+:::
+
+### 5. Report card
+
+Write three functions:
+
+- `print_header(school)` prints the school name between two lines of `=`.
+- `print_student(name, scores)` prints the name, the scores separated by commas, and the average with 1 decimal.
+- `print_report(school, students)` uses the other two to print a full report for a **dictionary** of `name → list of scores`.
+
+Call `print_report("School No. 7", {"Aziza": [5, 4, 5], "Bekzod": [3, 4, 4], "Dilnoza": [5, 5, 4]})`.
+
+::: details Solution
+```python
+def print_header(school):
+ line = "=" * 32
+ print(line)
+ print(school.center(32))
+ print(line)
+
+def print_student(name, scores):
+ scores_text = ", ".join(str(s) for s in scores)
+ average = sum(scores) / len(scores)
+ print(f"{name:<10} {scores_text:<12} avg {average:.1f}")
+
+def print_report(school, students):
+ print_header(school)
+ for name, scores in students.items():
+ print_student(name, scores)
+
+print_report("School No. 7", {"Aziza": [5, 4, 5], "Bekzod": [3, 4, 4], "Dilnoza": [5, 5, 4]})
+```
+
+```text
+================================
+ School No. 7
+================================
+Aziza 5, 4, 5 avg 4.7
+Bekzod 3, 4, 4 avg 3.7
+Dilnoza 5, 5, 4 avg 4.7
+```
+:::
+
+## Recap
+
+- `def name(parameters):` defines a function. `name(arguments)` calls it.
+- Parameters are the names in the definition, and arguments are the values you pass. They're matched in order.
+- A docstring (`"""…"""`) on the first line of the body documents the function, and `help()` shows it.
+- A function must be defined before the line that calls it **runs**.
+- Split big tasks into small functions that call each other.
+- `name` refers to the function, and `name()` calls it.
+
+## Further reading
+
+- [Python Tutorial - Defining functions](https://docs.python.org/3/tutorial/controlflow.html#defining-functions)
+- [PEP 257 - Docstring conventions](https://peps.python.org/pep-0257/)
diff --git a/docs/lessons/06-functions/02-parameters-and-arguments.md b/docs/lessons/06-functions/02-parameters-and-arguments.md
new file mode 100644
index 0000000..d49b71a
--- /dev/null
+++ b/docs/lessons/06-functions/02-parameters-and-arguments.md
@@ -0,0 +1,551 @@
+---
+title: Parameters and Arguments
+description: "Pass values to functions flexibly: positional and keyword arguments, default values, the mutable default trap, *args and **kwargs, and keyword-only parameters."
+---
+
+# Parameters and Arguments
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- The difference between **positional** and **keyword** arguments
+- How to make parameters optional with **default values**
+- Why you should never use a list as a default value
+- How `*args` and `**kwargs` accept any number of arguments
+- How `*` and `/` force arguments to be passed by keyword or by position
+:::
+
+## Why it matters
+
+Look at how flexible `print()` is: `print("a")`, `print("a", "b", "c")`, `print("a", end="")`, `print("a", "b", sep="-")`. It takes any number of values plus optional settings. With the techniques in this lesson, your own functions can be just as convenient to use.
+
+## Positional arguments
+
+By default, arguments are matched to parameters **by position**, first to first and second to second:
+
+```python
+def describe_pet(animal, name):
+ print(f"{name} is a {animal}.")
+
+describe_pet("cat", "Momo")
+describe_pet("Momo", "cat") # wrong order, wrong result
+```
+
+```text
+Momo is a cat.
+cat is a Momo.
+```
+
+Python can't tell that the order is wrong. Both are strings.
+
+## Keyword arguments
+
+You can name the parameter when calling. Then the **order doesn't matter**:
+
+```python
+def describe_pet(animal, name):
+ print(f"{name} is a {animal}.")
+
+describe_pet(name="Momo", animal="cat")
+describe_pet(animal="dog", name="Rex")
+```
+
+```text
+Momo is a cat.
+Rex is a dog.
+```
+
+Keyword arguments make calls self-explanatory, especially for numbers and booleans:
+
+```python
+def create_account(username, balance, is_admin):
+ print(f"{username}: balance {balance}, admin={is_admin}")
+
+create_account("aziza", 0, False) # what do 0 and False mean?
+create_account("aziza", balance=0, is_admin=False) # clear
+```
+
+You can mix both styles, but **positional arguments must come first**:
+
+```py
+create_account(username="aziza", 0, False)
+```
+
+```text
+SyntaxError: positional argument follows keyword argument
+```
+
+## Default values
+
+Give a parameter a default value with `=` in the definition. If the caller leaves it out, the default is used:
+
+```python
+def greet(name, greeting="Hello"):
+ print(f"{greeting}, {name}!")
+
+greet("Aziza")
+greet("Bekzod", "Salom")
+greet("Dilnoza", greeting="Good morning")
+```
+
+```text
+Hello, Aziza!
+Salom, Bekzod!
+Good morning, Dilnoza!
+```
+
+Parameters **with** defaults must come **after** parameters without them:
+
+```py
+def greet(greeting="Hello", name):
+ print(f"{greeting}, {name}!")
+```
+
+```text
+SyntaxError: parameter without a default follows parameter with a default
+```
+
+A realistic example with several options:
+
+```python
+def format_price(amount, currency="som", decimals=0, separator=","):
+ text = f"{amount:,.{decimals}f}".replace(",", separator)
+ return f"{text} {currency}"
+
+print(format_price(1250000))
+print(format_price(1250000, separator=" "))
+print(format_price(19.5, currency="USD", decimals=2))
+```
+
+```text
+1,250,000 som
+1 250 000 som
+19.50 USD
+```
+
+(`return` sends a value back to the caller. It's the topic of the next lesson.)
+
+Keyword arguments let callers skip over options they don't care about, like `separator=" "` without restating `currency` and `decimals`.
+
+## The mutable default trap
+
+Default values are created **once**, when the function is **defined**, not each time it's called. For numbers and strings, that doesn't matter. For a list or dictionary, it causes a famous bug:
+
+```python
+def add_item(item, basket=[]): # the same list is reused on every call!
+ basket.append(item)
+ return basket
+
+print(add_item("apple"))
+print(add_item("bread")) # expected ['bread']
+```
+
+```text
+['apple']
+['apple', 'bread']
+```
+
+The fix is to use `None` as the default and create a new list inside:
+
+```python
+def add_item(item, basket=None):
+ if basket is None:
+ basket = []
+ basket.append(item)
+ return basket
+
+print(add_item("apple"))
+print(add_item("bread"))
+```
+
+```text
+['apple']
+['bread']
+```
+
+**Rule:** never use a mutable value (`[]`, `{}`, `set()`) as a default. Use `None` and create the value inside the function.
+
+## `*args`: any number of positional arguments
+
+Put `*` before a parameter name to collect **all extra positional arguments** into a **tuple**:
+
+```python
+def total(*numbers):
+ print(f"received {numbers}")
+ return sum(numbers)
+
+print(total(5, 10))
+print(total(1, 2, 3, 4, 5))
+print(total())
+```
+
+```text
+received (5, 10)
+15
+received (1, 2, 3, 4, 5)
+15
+received ()
+0
+```
+
+The name `args` is just a convention. Use a descriptive name like `*numbers` or `*names` when you can.
+
+You can combine regular parameters with `*args`. The regular ones are filled first:
+
+```python
+def log(level, *messages):
+ print(f"[{level}]", " ".join(messages))
+
+log("INFO", "Server", "started")
+log("ERROR", "Disk", "is", "full")
+```
+
+```text
+[INFO] Server started
+[ERROR] Disk is full
+```
+
+### Unpacking a list into arguments
+
+The opposite direction also uses `*`: in a **call**, `*` spreads a list into separate arguments:
+
+```python
+def describe(name, age, city):
+ print(f"{name}, {age}, from {city}")
+
+record = ["Aziza", 20, "Tashkent"]
+describe(*record) # same as describe("Aziza", 20, "Tashkent")
+
+scores = [4, 8, 15]
+print(*scores) # print receives three arguments
+print(*scores, sep=" | ")
+```
+
+```text
+Aziza, 20, from Tashkent
+4 8 15
+4 | 8 | 15
+```
+
+## `**kwargs`: any number of keyword arguments
+
+Two stars collect **extra keyword arguments** into a **dictionary**:
+
+```python
+def create_profile(name, **details):
+ print(f"Profile for {name}")
+ for key, value in details.items():
+ print(f" {key}: {value}")
+
+create_profile("Aziza", age=20, city="Tashkent", language="Uzbek")
+```
+
+```text
+Profile for Aziza
+ age: 20
+ city: Tashkent
+ language: Uzbek
+```
+
+In a call, `**` unpacks a dictionary into keyword arguments:
+
+```python
+def greet(name, greeting="Hello"):
+ print(f"{greeting}, {name}!")
+
+options = {"name": "Bekzod", "greeting": "Salom"}
+greet(**options)
+```
+
+```text
+Salom, Bekzod!
+```
+
+## Keyword-only parameters
+
+Parameters listed **after** a bare `*` (or after `*args`) can **only** be given by keyword. This forces callers to write clear code for options that are easy to confuse:
+
+```python
+def transfer(amount, *, from_account, to_account):
+ print(f"Moving {amount:,} from {from_account} to {to_account}")
+
+transfer(500000, from_account="A-100", to_account="B-200")
+```
+
+```text
+Moving 500,000 from A-100 to B-200
+```
+
+```py
+def transfer(amount, *, from_account, to_account):
+ print(f"Moving {amount:,} from {from_account} to {to_account}")
+
+transfer(500000, "A-100", "B-200")
+```
+
+```text
+TypeError: transfer() takes 1 positional argument but 3 were given
+```
+
+Mixing up the two accounts would be a costly bug, so requiring names here is a good design.
+
+## Positional-only parameters
+
+The opposite also exists. Parameters **before** a `/` can **only** be given by position. You meet this first in `help()` output for built-in functions:
+
+```python
+help(len)
+```
+
+```text
+Help on built-in function len in module builtins:
+
+len(obj, /)
+ Return the number of items in a container.
+
+```
+
+The `/` after `obj` means "pass this by position only", so `len([1, 2])` works but `len(obj=[1, 2])` raises `TypeError: len() takes no keyword arguments`. You can use `/` in your own functions when the parameter names are not meaningful to callers and you want to be free to rename them later:
+
+```python
+def discount(price, percent, /, *, rounding=0):
+ return round(price * (100 - percent) / 100, rounding)
+
+print(discount(48500, 15))
+print(discount(48500, 15, rounding=-2))
+```
+
+```text
+41225.0
+41200.0
+```
+
+Here `price` and `percent` are positional-only, and `rounding` is keyword-only. Calling `discount(price=48000, percent=15)` raises `TypeError: discount() got some positional-only arguments passed as keyword arguments: 'price, percent'`. When you read `/` or `*` in documentation, you now know what they mean; in your own code you'll need `*` far more often than `/`.
+
+## The full order
+
+When you combine everything, parameters go in this order:
+
+```text
+def f(positional_only, /, positional, with_default=1, *args, keyword_only, **kwargs):
+```
+
+```python
+def example(a, b=2, *args, c, d=4, **kwargs):
+ print(f"a={a} b={b} args={args} c={c} d={d} kwargs={kwargs}")
+
+example(1, c=3)
+example(1, 20, 30, 40, c=3, e=5)
+```
+
+```text
+a=1 b=2 args=() c=3 d=4 kwargs={}
+a=1 b=20 args=(30, 40) c=3 d=4 kwargs={'e': 5}
+```
+
+In practice, most functions need only a few regular parameters and maybe some defaults. Reach for `*args` and `**kwargs` when you genuinely need flexibility.
+
+## Try it
+
+Experiment with calling `make_sandwich` in different ways: only the bread, extra fillings, keyword options.
+
+
+
+## Common mistakes
+
+### 1. Missing required arguments
+
+```py
+def greet(name, greeting):
+ print(f"{greeting}, {name}!")
+
+greet("Aziza")
+```
+
+```text
+TypeError: greet() missing 1 required positional argument: 'greeting'
+```
+
+**Fix:** pass the argument, or give the parameter a default.
+
+### 2. Unknown keyword
+
+```py
+def greet(name):
+ print(f"Hello, {name}!")
+
+greet(nmae="Aziza")
+```
+
+```text
+TypeError: greet() got an unexpected keyword argument 'nmae'
+```
+
+### 3. Same argument twice
+
+```py
+def greet(name, greeting="Hello"):
+ print(f"{greeting}, {name}!")
+
+greet("Aziza", name="Bekzod")
+```
+
+```text
+TypeError: greet() got multiple values for argument 'name'
+```
+
+`"Aziza"` already filled `name` by position.
+
+### 4. Forgetting the names of keyword-only arguments
+
+```py
+def transfer(amount, *, from_account, to_account):
+ print(f"Moving {amount:,} from {from_account} to {to_account}")
+
+transfer(500000)
+```
+
+```text
+TypeError: transfer() missing 2 required keyword-only arguments: 'from_account' and 'to_account'
+```
+
+The error says **keyword-only**, which tells you the fix: call `transfer(500000, from_account="A-100", to_account="B-200")`. Passing them by position doesn't work either, as the keyword-only section above showed.
+
+## Practice
+
+### 1. Power with a default
+
+Write `power(base, exponent=2)` that returns `base ** exponent`. Test `power(5)`, `power(2, 10)`, and `power(exponent=3, base=4)`.
+
+::: details Solution
+```python
+def power(base, exponent=2):
+ return base ** exponent
+
+print(power(5))
+print(power(2, 10))
+print(power(exponent=3, base=4))
+```
+
+```text
+25
+1024
+64
+```
+:::
+
+### 2. Flexible average
+
+Write `average(*numbers)` that returns the average of any number of values, or `0` if no values are given.
+
+::: details Solution
+```python
+def average(*numbers):
+ if not numbers:
+ return 0
+ return sum(numbers) / len(numbers)
+
+print(average(4, 8, 15))
+print(average())
+```
+:::
+
+### 3. HTML tag builder
+
+Write `tag(name, text, **attributes)` that returns an HTML-like string. For example, `tag("a", "Home", href="/", target="_blank")` returns `Home`, and `tag("p", "Hi")` returns `
Hi
`.
+
+::: details Solution
+```python
+def tag(name, text, **attributes):
+ attrs = "".join(f' {key}="{value}"' for key, value in attributes.items())
+ return f"<{name}{attrs}>{text}{name}>"
+
+print(tag("a", "Home", href="/", target="_blank"))
+print(tag("p", "Hi"))
+```
+:::
+
+### 4. Fix the shopping list
+
+This function should start a **new** list each time it's called without a list. Explain the bug, then fix it.
+
+```python
+def add_to_list(item, shopping=[]):
+ shopping.append(item)
+ return shopping
+
+monday = add_to_list("milk")
+tuesday = add_to_list("eggs")
+print(monday, tuesday)
+```
+
+::: details Solution
+It prints `['milk', 'eggs'] ['milk', 'eggs']`. The default list is created once, when the function is defined, so both calls append to the same list, and `monday` and `tuesday` are even the same object.
+
+```python
+def add_to_list(item, shopping=None):
+ if shopping is None:
+ shopping = []
+ shopping.append(item)
+ return shopping
+
+monday = add_to_list("milk")
+tuesday = add_to_list("eggs")
+print(monday, tuesday)
+```
+
+```text
+['milk'] ['eggs']
+```
+:::
+
+### 5. A configurable table printer
+
+Write `print_table(*rows, headers=None, width=10, align="left")`, where each row is a tuple of values:
+
+- if `headers` is given, print them first, followed by a line of `-`,
+- every cell is padded to `width` characters,
+- `align` is `"left"` or `"right"`.
+
+Make `headers`, `width`, and `align` **keyword-only**.
+
+```py
+print_table(("Tea", 15000), ("Coffee", 45000), headers=("Item", "Price"), align="right")
+```
+
+::: details Solution
+```python
+def print_table(*rows, headers=None, width=10, align="left"):
+ marker = "<" if align == "left" else ">"
+ if headers is not None:
+ print("".join(f"{str(value):{marker}{width}}" for value in headers))
+ print("-" * (width * len(headers)))
+ for row in rows:
+ print("".join(f"{str(value):{marker}{width}}" for value in row))
+
+print_table(("Tea", 15000), ("Coffee", 45000), headers=("Item", "Price"), align="right")
+```
+
+```text
+ Item Price
+--------------------
+ Tea 15000
+ Coffee 45000
+```
+
+Because `*rows` comes first, everything after it is automatically keyword-only. The format spec is built from variables: `f"{text:{marker}{width}}"` becomes `{text:>10}`. The same `join` expression formats the headers and each row.
+:::
+
+## Recap
+
+- **Positional** arguments match by order. **Keyword** arguments (`name=value`) match by name, and must come after positional ones.
+- **Defaults** (`param=value`) make parameters optional, and must come after required parameters.
+- Never use `[]` or `{}` as defaults. Use `None` and create the value inside.
+- `*args` collects extra positional arguments into a tuple, and `**kwargs` collects extra keyword arguments into a dictionary.
+- In a call, `*list` and `**dict` unpack values into arguments.
+- Parameters after `*` or `*args` are **keyword-only**; parameters before `/` are **positional-only**, as in `len(obj, /)`.
+
+## Further reading
+
+- [Python Tutorial - More on defining functions](https://docs.python.org/3/tutorial/controlflow.html#more-on-defining-functions)
+- [Python FAQ - Why are default values shared between objects?](https://docs.python.org/3/faq/programming.html#why-are-default-values-shared-between-objects)
diff --git a/docs/lessons/06-functions/03-return-values.md b/docs/lessons/06-functions/03-return-values.md
new file mode 100644
index 0000000..5028e90
--- /dev/null
+++ b/docs/lessons/06-functions/03-return-values.md
@@ -0,0 +1,500 @@
+---
+title: Return Values
+description: "Send results back from functions with return: return vs print, None, returning early, returning several values, boolean helper functions, and building programs from small functions."
+---
+
+# Return Values
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- How `return` sends a value back to the caller
+- The difference between **returning** and **printing**
+- What `None` is, and when a function returns it
+- How `return` ends a function early, and why that's useful
+- How to return several values at once
+:::
+
+## Why it matters
+
+Built-in functions like `len()`, `max()`, and `input()` don't print their results. They **give them back**, so you can store them, calculate with them, and pass them on: `total = len(items) * price`. Functions that return values are like building blocks. Functions that only print are dead ends. This lesson turns your functions into real building blocks.
+
+## `return` sends a value back
+
+```python
+def square(n):
+ return n * n
+
+result = square(7)
+print(result)
+print(square(3) + square(4))
+```
+
+```text
+49
+25
+```
+
+When Python reaches `return`, it:
+
+1. evaluates the expression after `return`,
+2. **leaves the function immediately**, and
+3. puts the value where the function was called.
+
+So `square(3) + square(4)` becomes `9 + 16`.
+
+## Return vs. print
+
+This is the most important distinction in the lesson:
+
+```python
+def add_print(a, b):
+ print(a + b) # shows the result, gives nothing back
+
+def add_return(a, b):
+ return a + b # gives the result back, shows nothing
+
+x = add_print(2, 3)
+y = add_return(2, 3)
+
+print(f"x = {x}")
+print(f"y = {y}")
+```
+
+```text
+5
+x = None
+y = 5
+```
+
+`add_print` displayed `5` on screen, but the program can't **use** that value: `x` is `None`. `add_return` printed nothing by itself, but `y` holds `5`, ready to be used.
+
+::: warning The interactive shell makes return look like print
+If you type the same calls into the interactive `>>>` shell, both seem to "show" 5:
+
+```text
+>>> add_print(2, 3)
+5
+>>> add_return(2, 3)
+5
+```
+
+The shell echoes the value of every expression you type. A script, and the editor on this site, does not: there `add_return(2, 3)` on its own line shows nothing.
+:::
+
+| `print()` inside a function | `return` |
+|---|---|
+| shows something to the **user** | gives a value to the **program** |
+| the value is lost after it's displayed | the value can be stored, combined, and tested |
+
+A good habit: functions **calculate and return**. The code that calls them decides whether to print.
+
+```python
+def calculate_total(prices, tax_rate):
+ subtotal = sum(prices)
+ return subtotal * (1 + tax_rate)
+
+total = calculate_total([15000, 45000, 8000], 0.12)
+print(f"Total: {total:,.0f} som") # the caller decides how to show it
+if total > 50000:
+ print("You qualify for free delivery!") # ...and can make decisions with it
+```
+
+```text
+Total: 76,160 som
+You qualify for free delivery!
+```
+
+## `None`: the "no value" value
+
+A function without `return`, or with a bare `return`, gives back `None`:
+
+```python
+def say_hi():
+ print("Hi")
+
+result = say_hi()
+print(result)
+print(type(result))
+```
+
+```text
+Hi
+None
+
+```
+
+`None` is Python's way of saying "nothing here". It's falsy, and the recommended way to check for it is `is None`:
+
+```python
+def find_first_negative(numbers):
+ for n in numbers:
+ if n < 0:
+ return n
+ return None # nothing found (writing this makes it explicit)
+
+result = find_first_negative([4, 7, 1])
+if result is None:
+ print("No negative numbers")
+else:
+ print(f"Found {result}")
+```
+
+```text
+No negative numbers
+```
+
+Use `is None` rather than `if not result:`, because `0` is also falsy but is a perfectly valid result.
+
+## Returning early
+
+`return` exits the function **immediately**, even from inside a loop. That makes searches simple, with no `break` or flag needed:
+
+```python
+def contains_digit(text):
+ for char in text:
+ if char.isdigit():
+ return True # found one: stop right here
+ return False # the loop finished without finding any
+
+print(contains_digit("abc2def"))
+print(contains_digit("abcdef"))
+```
+
+```text
+True
+False
+```
+
+It's also great for handling special cases at the start. These checks are called **guard clauses**:
+
+```python
+def divide(a, b):
+ if b == 0:
+ return None # guard: handle the problem case first
+ return a / b
+
+print(divide(10, 4))
+print(divide(10, 0))
+```
+
+```text
+2.5
+None
+```
+
+Guard clauses keep the main logic un-indented and easy to read.
+
+Returning `None` for a problem is fine for small programs, but the caller can forget to check and later try to do maths with `None`. For real errors you'll **raise an exception** instead, which stops the program with a clear message; *Handling Exceptions* shows how.
+
+## Returning several values
+
+Separate values with commas to return a **tuple**, and unpack it when calling (see *Tuples and Unpacking*):
+
+```python
+def min_max_average(numbers):
+ return min(numbers), max(numbers), sum(numbers) / len(numbers)
+
+low, high, avg = min_max_average([72, 95, 58, 88])
+print(f"low {low}, high {high}, average {avg:.1f}")
+```
+
+```text
+low 58, high 95, average 78.2
+```
+
+For more than three or four values, returning a dictionary is often clearer, because the caller then uses names instead of positions:
+
+```python
+def analyze(text):
+ words = text.split()
+ return {
+ "characters": len(text),
+ "words": len(words),
+ "longest": max(words, key=len),
+ }
+
+stats = analyze("Python functions return useful values")
+print(stats["words"], stats["longest"])
+```
+
+```text
+5 functions
+```
+
+## Boolean functions
+
+Functions that answer a yes/no question should return `True` or `False`. Name them like questions, `is_…`, `has_…`, `can_…`, so the code reads naturally:
+
+```python
+def is_leap_year(year):
+ return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0
+
+def can_vote(age):
+ return age >= 18
+
+for year in [2024, 2026]:
+ if is_leap_year(year):
+ print(f"{year} is a leap year")
+
+print(can_vote(17))
+```
+
+```text
+2024 is a leap year
+False
+```
+
+Notice `return age >= 18`: the comparison already **is** a boolean. There's no need for `if age >= 18: return True else: return False`.
+
+## Composing functions
+
+Because returned values can be passed straight into other functions, small functions combine into bigger ones:
+
+```python
+def celsius_to_fahrenheit(c):
+ return c * 9 / 5 + 32
+
+def describe_temperature(c):
+ if c < 0:
+ return "freezing"
+ if c < 20:
+ return "cool"
+ if c < 30:
+ return "warm"
+ return "hot"
+
+def weather_report(city, c):
+ f = celsius_to_fahrenheit(c)
+ return f"{city}: {c}°C / {f:.0f}°F, {describe_temperature(c)}"
+
+print(weather_report("Tashkent", 34))
+print(weather_report("Moscow", -5))
+```
+
+```text
+Tashkent: 34°C / 93°F, hot
+Moscow: -5°C / 23°F, freezing
+```
+
+Each function is small, can be tested on its own, and has one clear job. A function can even call **itself**, which is the idea behind *Recursion*, the lesson after *Variable Scope*. That's the direction the *Designing Good Functions* lesson develops further.
+
+::: tip Quick checks with assert
+`assert` stops the program with an error if a condition is false. It's a simple way to check that a function returns what you expect:
+
+```python
+def square(n):
+ return n * n
+
+assert square(3) == 9
+assert square(-2) == 4
+print("All checks passed")
+```
+:::
+
+## Try it
+
+Complete the grading functions and test them with different scores.
+
+
+
+## Common mistakes
+
+### 1. Printing instead of returning
+
+```py
+def double(n):
+ print(n * 2)
+
+result = double(5) + 1
+```
+
+```text
+10
+TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
+```
+
+`double(5)` printed `10` but returned `None`. **Fix:** `return n * 2`.
+
+### 2. Forgetting `return` in one branch
+
+```python
+def sign(n):
+ if n > 0:
+ return "positive"
+ elif n < 0:
+ return "negative"
+ # forgot the zero case
+
+print(sign(0)) # None
+```
+
+Make sure **every path** through the function returns a value.
+
+### 3. Returning inside the loop too early
+
+```python
+def all_positive(numbers):
+ for n in numbers:
+ if n > 0:
+ return True # decides after looking at only the first item!
+ return False
+
+print(all_positive([5, -1, -2])) # True (wrong)
+```
+
+**Fix:** return `False` as soon as you find a non-positive number, and return `True` only **after** the loop:
+
+```python
+def all_positive(numbers):
+ for n in numbers:
+ if n <= 0:
+ return False
+ return True
+
+print(all_positive([5, -1, -2])) # False
+```
+
+### 4. Ignoring the returned value
+
+```python
+name = "aziza"
+name.upper() # the result is thrown away
+print(name)
+```
+
+```text
+aziza
+```
+
+`upper()` **returns** a new string; it doesn't change `name`. The same goes for `sorted(items)` and your own functions. **Fix:** store or use the result: `name = name.upper()`.
+
+## Practice
+
+### 1. Area of a circle
+
+Write `circle_area(radius)` that returns `π × r²` using `math.pi`. Print the area for radius `3`, rounded to 2 decimals.
+
+::: details Solution
+```python
+import math
+
+def circle_area(radius):
+ return math.pi * radius ** 2
+
+print(round(circle_area(3), 2))
+```
+
+```text
+28.27
+```
+
+`import math` gives you access to the `math` module, which holds `math.pi`. The *Modules and Imports* lesson explains imports in detail.
+:::
+
+### 2. Is it even?
+
+Write `is_even(n)` that returns `True` or `False`, **without** an `if` statement. Use it to build a list of the even numbers from 1 to 10.
+
+::: details Solution
+```python
+def is_even(n):
+ return n % 2 == 0
+
+evens = [n for n in range(1, 11) if is_even(n)]
+print(evens)
+```
+:::
+
+### 3. Full name
+
+Write `full_name(first, last, middle="")` that returns a properly capitalized name, with the middle name included only if it's given. `full_name("aziza", "karimova")` → `"Aziza Karimova"`, and `full_name("bekzod", "tursunov", "alievich")` → `"Bekzod Alievich Tursunov"`.
+
+::: details Solution
+```python
+def full_name(first, last, middle=""):
+ if middle:
+ return f"{first.title()} {middle.title()} {last.title()}"
+ return f"{first.title()} {last.title()}"
+
+assert full_name("aziza", "karimova") == "Aziza Karimova"
+assert full_name("bekzod", "tursunov", "alievich") == "Bekzod Alievich Tursunov"
+print("OK")
+```
+:::
+
+### 4. Find the index
+
+Write `index_of(items, target)` that returns the position of the first occurrence of `target`, or `-1` if it's not there. Don't use `.index()`.
+
+::: details Solution
+```python
+def index_of(items, target):
+ for i, item in enumerate(items):
+ if item == target:
+ return i
+ return -1
+
+assert index_of(["a", "b", "c"], "c") == 2
+assert index_of(["a", "b", "c"], "z") == -1
+assert index_of([], "a") == -1
+print("OK")
+```
+:::
+
+### 5. Password strength
+
+Write `check_password(password)` that returns a **tuple** `(is_strong, problems)`, where `problems` is a list of messages for every rule broken:
+
+- at least 8 characters
+- at least one digit
+- at least one uppercase letter
+- at least one lowercase letter
+
+Then write code that calls it for `"abc"`, `"password1"`, and `"Tea4Two!"` and prints the results nicely.
+
+::: details Solution
+```python
+def check_password(password):
+ problems = []
+ if len(password) < 8:
+ problems.append("use at least 8 characters")
+ if not any(ch.isdigit() for ch in password):
+ problems.append("add a digit")
+ if not any(ch.isupper() for ch in password):
+ problems.append("add an uppercase letter")
+ if not any(ch.islower() for ch in password):
+ problems.append("add a lowercase letter")
+ return len(problems) == 0, problems
+
+for pw in ["abc", "password1", "Tea4Two!"]:
+ is_strong, problems = check_password(pw)
+ if is_strong:
+ print(f"{pw}: strong")
+ else:
+ print(f"{pw}: weak ({'; '.join(problems)})")
+```
+
+```text
+abc: weak (use at least 8 characters; add a digit; add an uppercase letter)
+password1: weak (add an uppercase letter)
+Tea4Two!: strong
+```
+
+The function doesn't print anything. The calling code decides how to show the result, so the same function could also power a website form.
+:::
+
+## Recap
+
+- `return value` ends the function and gives the value to the caller, where it can be stored and used.
+- **Return** values for the program to use, and **print** only for final output to the user.
+- Without `return`, a function gives back `None`. Check for it with `is None`.
+- `return` exits immediately, which is useful for searches and **guard clauses**.
+- `return a, b` returns a tuple, so unpack it with `x, y = f()`. Use a dictionary for many named results.
+- Name boolean functions like questions, and return the condition directly: `return age >= 18`.
+
+## Further reading
+
+- [Python Tutorial - Defining functions (return)](https://docs.python.org/3/tutorial/controlflow.html#defining-functions)
+- [The `return` statement](https://docs.python.org/3/reference/simple_stmts.html#the-return-statement)
+- [The `assert` statement](https://docs.python.org/3/reference/simple_stmts.html#the-assert-statement)
diff --git a/docs/lessons/06-functions/04-scope.md b/docs/lessons/06-functions/04-scope.md
new file mode 100644
index 0000000..0080aa5
--- /dev/null
+++ b/docs/lessons/06-functions/04-scope.md
@@ -0,0 +1,523 @@
+---
+title: Variable Scope
+description: "Understand where variables live: local and global scope, the LEGB lookup rule, UnboundLocalError, the global and nonlocal keywords, and why changing a list inside a function affects the caller."
+---
+
+# Variable Scope
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- The difference between **local** and **global** variables
+- How Python finds a name: the **LEGB** rule
+- Why assigning inside a function creates a local variable, and what `UnboundLocalError` means
+- When `global` and `nonlocal` are needed, and why to avoid them
+- Why functions can **change** a list you pass in, but not **replace** it
+:::
+
+## Why it matters
+
+As programs grow, the same variable names get reused: `total`, `count`, `name`, `result`. If every variable were visible everywhere, a function could accidentally overwrite a value somewhere else, and bugs would be very hard to find. **Scope** is the set of rules that decides where each variable can be seen and changed. It keeps functions independent.
+
+## Local variables
+
+Variables created inside a function, including its parameters, are **local**: they exist only while the function runs, and only inside it.
+
+```python
+def calculate_area(width, height):
+ area = width * height # local variable
+ return area
+
+print(calculate_area(4, 5))
+```
+
+```py
+def calculate_area(width, height):
+ area = width * height
+ return area
+
+calculate_area(4, 5)
+print(area)
+```
+
+```text
+NameError: name 'area' is not defined
+```
+
+Once the function returns, `area`, `width`, and `height` are gone. Each call gets a fresh set of local variables.
+
+This is a **feature**: two functions can both use a variable called `total` without interfering.
+
+## Global variables
+
+Variables created at the top level of a file, outside all functions, are **global**. Functions can **read** them:
+
+```python
+TAX_RATE = 0.12 # global
+
+def price_with_tax(price):
+ return price * (1 + TAX_RATE) # reading a global: fine
+
+print(round(price_with_tax(10000)))
+```
+
+```text
+11200
+```
+
+Reading global **constants** like this is common and fine.
+
+### Blocks don't create a scope
+
+Only functions (and modules, and classes) create a new scope. An `if`, `for`, or `while` block does **not**, so names assigned inside it are still there afterwards:
+
+```python
+for i in range(3):
+ square = i * i
+
+if square > 0:
+ message = "positive"
+
+print(i, square, message)
+```
+
+```text
+2 4 positive
+```
+
+After the loop, `i` keeps its last value, and `message` exists because the `if` ran. If you've used languages where every `{ }` block has its own variables, this is a surprise. In Python, when you think about scope, think about **functions**.
+
+## Assigning inside a function creates a local variable
+
+Here's where people get surprised. If a function **assigns** to a name, that name is **local** for the whole function, even if a global variable has the same name:
+
+```python
+count = 10
+
+def reset():
+ count = 0 # creates a NEW local 'count'
+ print(f"inside: {count}")
+
+reset()
+print(f"outside: {count}")
+```
+
+```text
+inside: 0
+outside: 10
+```
+
+The global `count` was never touched. The function had its own separate `count`.
+
+### UnboundLocalError
+
+The same rule causes this error:
+
+```py
+count = 10
+
+def increment():
+ count = count + 1 # 'count' is local here, because it's assigned
+ return count
+
+increment()
+```
+
+```text
+UnboundLocalError: cannot access local variable 'count' where it is not associated with a value
+```
+
+Python decides **before running** the function that `count` is local, because it's assigned somewhere in the function. So when `count + 1` runs, the local `count` doesn't have a value yet.
+
+The best fix is to **pass the value in and return the new value**:
+
+```python
+count = 10
+
+def increment(value):
+ return value + 1
+
+count = increment(count)
+print(count)
+```
+
+```text
+11
+```
+
+## The `global` keyword (use sparingly)
+
+`global` tells Python that a name inside a function refers to the global variable:
+
+```python
+visits = 0
+
+def record_visit():
+ global visits
+ visits += 1
+
+record_visit()
+record_visit()
+print(visits)
+```
+
+```text
+2
+```
+
+It works, but **avoid it** in most code:
+
+- Any function could change the value, so bugs are hard to trace.
+- The function depends on hidden state, which makes it hard to reuse and test.
+
+Prefer parameters and return values. Later, *Classes and Objects* shows a clean way to keep state together with the functions that change it.
+
+## How Python finds a name: LEGB
+
+When your code uses a name, Python searches these scopes **in order** and uses the first match:
+
+| | Scope | What's there |
+|---|---|---|
+| **L** | Local | names assigned in the current function |
+| **E** | Enclosing | names in any outer functions (when a function is defined inside another) |
+| **G** | Global | names at the top level of the file |
+| **B** | Built-in | Python's built-in names: `print`, `len`, `sum`, … |
+
+```python
+x = "global"
+
+def outer():
+ x = "enclosing"
+
+ def inner():
+ x = "local"
+ print(x)
+
+ inner()
+ print(x)
+
+outer()
+print(x)
+```
+
+```text
+local
+enclosing
+global
+```
+
+The **B** level is why a global named `list` or `sum` hides the built-in one (Common mistake 4).
+
+## `nonlocal`: changing an enclosing variable
+
+For nested functions, `nonlocal` is the equivalent of `global`. It lets the inner function assign to a variable of the **enclosing** function:
+
+```python
+def make_counter():
+ count = 0
+
+ def increase():
+ nonlocal count
+ count += 1
+ return count
+
+ return increase
+
+counter = make_counter()
+print(counter())
+print(counter())
+print(counter())
+```
+
+```text
+1
+2
+3
+```
+
+`make_counter` returns the inner function, and that function **remembers** `count` even after `make_counter` has finished. This is called a **closure**. You don't need it often as a beginner, but you'll meet it again in *Lambdas and Higher-Order Functions*.
+
+## Mutating vs. reassigning arguments
+
+When you pass a list or dictionary to a function, the parameter refers to the **same object**, just like `b = a` in *Lists*. That leads to two very different situations:
+
+```python
+def add_bonus(scores):
+ scores.append(100) # MUTATES the same list: the caller sees it
+
+def replace_scores(scores):
+ scores = [0, 0, 0] # REBINDS the local name only: the caller doesn't see it
+
+my_scores = [80, 90]
+
+add_bonus(my_scores)
+print(my_scores)
+
+replace_scores(my_scores)
+print(my_scores)
+```
+
+```text
+[80, 90, 100]
+[80, 90, 100]
+```
+
+- **Changing** the object, with a method such as `append`, `remove` or `sort`, or with item assignment such as `d[key] = …`, affects the caller's object.
+- **Assigning** a new value to the parameter name only changes the local name.
+
+Numbers and strings are immutable, so a function can never change the caller's number or string. It can only return a new one.
+
+::: tip Don't surprise the caller
+A function that quietly changes the list you gave it can cause confusing bugs. Either make it obvious (name it `add_bonus_in_place`, and don't return anything), or work on a copy and **return a new list**:
+
+```python
+def with_bonus(scores):
+ return scores + [100] # new list; the original stays unchanged
+
+original = [80, 90]
+updated = with_bonus(original)
+print(original, updated)
+```
+:::
+
+## Try it
+
+Predict the output before running. Then remove `global total` and see what error you get.
+
+
+
+## Common mistakes
+
+### 1. `+=` on a global inside a function
+
+```py
+visits = 0
+
+def record_visit():
+ visits += 1
+
+record_visit()
+```
+
+```text
+UnboundLocalError: cannot access local variable 'visits' where it is not associated with a value
+```
+
+`visits += 1` is an assignment, so `visits` is local for the whole function, and it has no value yet when `+=` reads it. **Fix:** pass the value in and return the new one (`visits = record_visit(visits)`). Use `global` only when you really must.
+
+### 2. Expecting reassignment to change the caller's variable
+
+```python
+def clear(items):
+ items = []
+
+data = [1, 2, 3]
+clear(data)
+print(data)
+```
+
+```text
+[1, 2, 3]
+```
+
+`items = []` only points the local name at a new list. **Fix:** `items.clear()` mutates the list in place, or return a new list and reassign it in the caller.
+
+### 3. Accidentally changing the caller's list
+
+```python
+def top_three(scores):
+ scores.sort(reverse=True)
+ return scores[:3]
+
+results = [72, 95, 58, 88]
+print(top_three(results))
+print(results)
+```
+
+```text
+[95, 88, 72]
+[95, 88, 72, 58]
+```
+
+The function answered correctly, but it also reordered the caller's `results`. **Fix:** work on a copy, `sorted(scores, reverse=True)[:3]`, if the caller shouldn't be affected.
+
+### 4. Shadowing built-ins
+
+```py
+def average(list):
+ return sum(list) / len(list)
+
+print(average([1, 2, 3]))
+print(list("abc")) # works here, because the parameter was local
+
+list = [1, 2] # but at the top level...
+print(list("abc"))
+```
+
+```text
+2.0
+['a', 'b', 'c']
+TypeError: 'list' object is not callable
+```
+
+**Fix:** use names like `values` or `numbers` instead of `list`, `str`, `sum`, or `max`.
+
+## Practice
+
+### 1. Predict the output
+
+```python
+name = "Global"
+
+def show():
+ name = "Local"
+ print(name)
+
+show()
+print(name)
+```
+
+::: details Solution
+```text
+Local
+Global
+```
+
+Assigning `name` inside `show` created a separate local variable.
+:::
+
+### 2. Fix without global
+
+This code raises `UnboundLocalError`. Fix it **without** using `global`.
+
+```py
+score = 0
+
+def add_points(points):
+ score = score + points
+
+add_points(10)
+add_points(5)
+print(score)
+```
+
+::: details Solution
+```python
+score = 0
+
+def add_points(current, points):
+ return current + points
+
+score = add_points(score, 10)
+score = add_points(score, 5)
+print(score)
+```
+
+```text
+15
+```
+:::
+
+### 3. Which ones change?
+
+Predict the output, then run it.
+
+```python
+def modify(numbers, text, count):
+ numbers.append(4)
+ text = text.upper()
+ count += 1
+
+nums = [1, 2, 3]
+word = "hello"
+n = 10
+
+modify(nums, word, n)
+print(nums, word, n)
+```
+
+::: details Solution
+```text
+[1, 2, 3, 4] hello 10
+```
+
+Only the list changed, because `append` mutates the shared object. `text.upper()` creates a new string assigned to the local `text`, and `count += 1` rebinds the local `count`. Strings and numbers are immutable.
+:::
+
+### 4. Non-mutating version
+
+Write `remove_negatives(numbers)` that returns a **new** list without negative numbers and leaves the original unchanged. Prove it with `assert`.
+
+::: details Solution
+```python
+def remove_negatives(numbers):
+ return [n for n in numbers if n >= 0]
+
+original = [3, -1, 4, -1, 5]
+cleaned = remove_negatives(original)
+
+assert cleaned == [3, 4, 5]
+assert original == [3, -1, 4, -1, 5]
+print("OK")
+```
+:::
+
+### 5. Bank account closure
+
+Write `make_account(balance)` that returns **two** functions, `deposit(amount)` and `withdraw(amount)`, which share the same balance using `nonlocal`. Both return the new balance, and `withdraw` refuses (returns the balance unchanged and prints a message) if there isn't enough money.
+
+```py
+deposit, withdraw = make_account(100000)
+print(deposit(50000)) # 150000
+print(withdraw(30000)) # 120000
+print(withdraw(500000)) # prints a warning, returns 120000
+```
+
+::: details Solution
+```python
+def make_account(balance):
+ def deposit(amount):
+ nonlocal balance
+ balance += amount
+ return balance
+
+ def withdraw(amount):
+ nonlocal balance
+ if amount > balance:
+ print("Insufficient funds")
+ return balance
+ balance -= amount
+ return balance
+
+ return deposit, withdraw
+
+deposit, withdraw = make_account(100000)
+print(deposit(50000))
+print(withdraw(30000))
+print(withdraw(500000))
+```
+
+```text
+150000
+120000
+Insufficient funds
+120000
+```
+
+The parameter `balance` belongs to `make_account`, and both inner functions share it through `nonlocal`. Nothing outside can change the balance directly. In *Classes and Objects* you'll build the same thing with a class.
+:::
+
+## Recap
+
+- Variables assigned inside a function (including parameters) are **local**: they're created on each call and gone afterwards.
+- Top-level variables are **global**. Functions can read them, and reading global constants is fine.
+- **Assigning** to a name anywhere in a function makes it local for the whole function, and using it before assigning gives `UnboundLocalError`.
+- Python looks names up in the order **L**ocal → **E**nclosing → **G**lobal → **B**uilt-in.
+- `global` and `nonlocal` allow assignment to outer variables. Prefer parameters and return values instead.
+- Passing a list shares the object: **mutating** it affects the caller, but **reassigning** the parameter doesn't.
+
+## Further reading
+
+- [Python Tutorial - Scopes and namespaces](https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces)
+- [Python FAQ - What are the rules for local and global variables?](https://docs.python.org/3/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python)
+- [Python FAQ - Why am I getting an UnboundLocalError?](https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value)
diff --git a/docs/lessons/06-functions/05-recursion.md b/docs/lessons/06-functions/05-recursion.md
new file mode 100644
index 0000000..f4cacc0
--- /dev/null
+++ b/docs/lessons/06-functions/05-recursion.md
@@ -0,0 +1,405 @@
+---
+title: Recursion
+description: "Write functions that call themselves: base and recursive cases, how the call stack unwinds, RecursionError, and when recursion beats a loop (nested data like folders and lists of lists)."
+---
+
+# Recursion
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- What it means for a function to **call itself**, and why that isn't an infinite loop
+- The two parts every recursive function needs: a **base case** and a **recursive case**
+- How Python keeps track of the calls on the **call stack**, and what `RecursionError` means
+- When a loop is simpler, and when recursion is the natural tool: **nested** data
+:::
+
+## Why it matters
+
+A folder contains files and other folders, which contain files and other folders. A list can contain lists that contain lists. A family tree, a menu with submenus, a company org chart: the data is shaped like itself at every level. A `for` loop handles one level. To handle *any* depth, you write a function that solves the big problem by solving a smaller copy of the same problem, and calls **itself** to do it. That idea is **recursion**, and it appears in every file manager, JSON parser, and search engine.
+
+## A function that calls itself
+
+Nothing stops a function from calling the function it's defined in. Here is a countdown written without a loop:
+
+```python
+def countdown(n):
+ if n == 0:
+ print("Liftoff!")
+ return
+ print(n)
+ countdown(n - 1)
+
+countdown(3)
+```
+
+```text
+3
+2
+1
+Liftoff!
+```
+
+`countdown(3)` prints `3` and calls `countdown(2)`, which prints `2` and calls `countdown(1)`, which prints `1` and calls `countdown(0)`. That call prints `Liftoff!` and returns without calling anything, so the chain stops. Each call works on a **smaller** version of the problem, and the smallest version is handled directly.
+
+## Base case and recursive case
+
+Every recursive function has the same two parts:
+
+- The **base case** is the smallest input, which the function answers **without** calling itself. In `countdown`, that is `n == 0`.
+- The **recursive case** does a little work and then calls the function on a **smaller** input, moving toward the base case.
+
+The classic example is the factorial. `5!` is `5 × 4 × 3 × 2 × 1`, and it can be described in terms of itself: `5!` is `5 × 4!`.
+
+```python
+def factorial(n):
+ if n <= 1: # base case
+ return 1
+ return n * factorial(n - 1) # recursive case
+
+print(factorial(5))
+print(factorial(20))
+```
+
+```text
+120
+2432902008176640000
+```
+
+Read the recursive case as a **trust** statement: "assume `factorial(n - 1)` already works, then my job is only to multiply by `n`." You don't trace all the calls in your head. You check that the base case is right and that each step moves toward it.
+
+## What happens on the call stack
+
+When a function calls itself, the first call does **not** end. It waits, with its own local variables, until the inner call returns. Python keeps the waiting calls on the **call stack**, the same structure you saw in a traceback in *Reading Errors and Debugging*. Prints with indentation make the stack visible:
+
+```python
+def factorial(n, depth=0):
+ indent = " " * depth
+ print(f"{indent}factorial({n}) starts")
+ if n <= 1:
+ print(f"{indent}factorial({n}) returns 1")
+ return 1
+ result = n * factorial(n - 1, depth + 1)
+ print(f"{indent}factorial({n}) returns {result}")
+ return result
+
+factorial(4)
+```
+
+```text
+factorial(4) starts
+ factorial(3) starts
+ factorial(2) starts
+ factorial(1) starts
+ factorial(1) returns 1
+ factorial(2) returns 2
+ factorial(3) returns 6
+factorial(4) returns 24
+```
+
+The calls go **down** to the base case and the results come back **up**: `1`, then `2 × 1`, then `3 × 2`, then `4 × 6`. Each level has its own `n`, exactly as *Variable Scope* promised: locals belong to one call.
+
+## When there is no base case
+
+If the function never reaches a base case, the stack grows until Python stops it:
+
+```py
+def countdown(n):
+ print(n)
+ countdown(n - 1) # no base case: n just keeps shrinking
+
+countdown(3)
+```
+
+```text
+3
+2
+1
+0
+-1
+...
+ File "main.py", line 3, in countdown
+ countdown(n - 1) # no base case: n just keeps shrinking
+ ~~~~~~~~~^^^^^^^
+ [Previous line repeated 996 more times]
+RecursionError: maximum recursion depth exceeded
+```
+
+The limit is about 1,000 nested calls (`sys.getrecursionlimit()`), and Python has no trick to remove it: a recursive function that counts to a million will fail where a loop wouldn't. That is the trade-off. Use recursion when the **depth** is small, like the depth of a folder tree, not the length of a list.
+
+## Recursion or a loop?
+
+Everything `countdown` and `factorial` do, a `for` loop does more simply, and you should write the loop. Recursion earns its place when the data is **nested to an unknown depth**. Suppose an order can contain items *or bundles*, and a bundle can contain bundles:
+
+```python
+def total(item):
+ if isinstance(item, list): # a bundle: add up its parts
+ return sum(total(part) for part in item)
+ return item # a single price
+
+order = [15000, [8000, 8000], [12000, [5000, 5000]]]
+print(total(order))
+```
+
+```text
+53000
+```
+
+A loop with `if isinstance(...)` inside would handle two levels, then three, and still be wrong for four. The recursive version handles any depth in three lines, because a bundle is just a smaller order. The same shape works for the nested dictionaries from *Nested Data*, such as a folder tree:
+
+```python
+folder = {
+ "docs": {"plan.md": 4, "notes.txt": 2},
+ "photos": {"trip": {"bukhara.jpg": 3200, "khiva.jpg": 2900}, "cat.jpg": 800},
+ "readme.md": 1,
+}
+
+def total_size(item):
+ if isinstance(item, dict): # a folder: add up its contents
+ return sum(total_size(child) for child in item.values())
+ return item # a file: its size in KB
+
+def show(item, name="/", depth=0):
+ print(" " * depth + name)
+ if isinstance(item, dict):
+ for child_name, child in item.items():
+ show(child, child_name, depth + 1)
+
+show(folder)
+print(total_size(folder), "KB")
+```
+
+```text
+/
+ docs
+ plan.md
+ notes.txt
+ photos
+ trip
+ bukhara.jpg
+ khiva.jpg
+ cat.jpg
+ readme.md
+6907 KB
+```
+
+`show` passes `depth + 1` down so each level is indented one step more: the extra parameter carries information **down** the calls, while the return value of `total_size` carries information back **up**.
+
+## Try it
+
+Change the order structure, add a deeper bundle, or make `show` print file sizes next to file names.
+
+
+
+## Common mistakes
+
+### 1. A base case that doesn't stop the function
+
+```py
+def countdown(n):
+ if n == 0:
+ print("Liftoff!")
+ print(n) # Bad: this line still runs when n == 0
+ countdown(n - 1) # ... and so does this one
+
+countdown(2)
+```
+
+```text
+2
+1
+Liftoff!
+0
+-1
+...
+RecursionError: maximum recursion depth exceeded
+```
+
+The base case printed its message but didn't `return`, so the recursive call happened anyway. **Fix:** end the base case with `return` (or put the recursive case in an `else`).
+
+### 2. Forgetting to `return` the recursive result
+
+```py
+def factorial(n):
+ if n <= 1:
+ return 1
+ n * factorial(n - 1) # Bad: the result is computed and thrown away
+
+print(factorial(5))
+```
+
+```text
+TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
+```
+
+Without `return`, the recursive case returns `None`, and the level above tries to multiply by it. **Fix:** `return n * factorial(n - 1)`. This is the same "print or return" trap from *Return Values*, one level deeper.
+
+### 3. Not moving toward the base case
+
+```py
+def digit_sum(n):
+ if n < 10:
+ return n
+ return n % 10 + digit_sum(n) # Bad: same n every time
+
+print(digit_sum(2026))
+```
+
+```text
+RecursionError: maximum recursion depth exceeded
+```
+
+Every recursive call must receive a **smaller** problem: `n // 10` here, `n - 1` in `countdown`, `text[1:]` for a string, a child folder for a tree. If the argument never changes, the base case is never reached.
+
+## Practice
+
+### 1. Digit sum
+
+Write `digit_sum(n)` that returns the sum of the digits of a non-negative integer using recursion, and print the results for `2026`, `7`, and `999999`. Hint: `n % 10` is the last digit and `n // 10` is the rest.
+
+::: details Solution
+```python
+def digit_sum(n):
+ if n < 10:
+ return n
+ return n % 10 + digit_sum(n // 10)
+
+print(digit_sum(2026), digit_sum(7), digit_sum(999999))
+```
+
+```text
+10 7 54
+```
+
+The base case is a single digit. Each call peels off the last digit and hands the rest to a smaller call.
+:::
+
+### 2. Power
+
+Write `power(base, exponent)` that computes `base ** exponent` for a non-negative `exponent` without using `**` or a loop. Print `power(2, 10)`, `power(5, 3)`, and `power(7, 0)`.
+
+::: details Solution
+```python
+def power(base, exponent):
+ if exponent == 0:
+ return 1
+ return base * power(base, exponent - 1)
+
+print(power(2, 10), power(5, 3), power(7, 0))
+```
+
+```text
+1024 125 1
+```
+
+Anything to the power `0` is `1`: that is the base case, and it also makes `power(7, 0)` work.
+:::
+
+### 3. Reverse a string
+
+Write `reverse(text)` that returns the string backwards, using recursion rather than slicing with `[::-1]`. Print `repr(reverse(word))` for `"Samarkand"`, `"non"`, `"a"`, and `""`.
+
+::: details Solution
+```python
+def reverse(text):
+ if len(text) <= 1:
+ return text
+ return reverse(text[1:]) + text[0]
+
+for word in ["Samarkand", "non", "a", ""]:
+ print(repr(reverse(word)))
+```
+
+```text
+'dnakramaS'
+'non'
+'a'
+''
+```
+
+A string of length 0 or 1 is already reversed. Otherwise, reverse everything after the first character, then put the first character at the end.
+:::
+
+### 4. Flatten a nested list
+
+Write `flatten(items)` that turns `[1, [2, 3], [4, [5, [6]]], 7]` into `[1, 2, 3, 4, 5, 6, 7]`, whatever the depth. Print the result.
+
+::: details Solution
+```python
+def flatten(items):
+ flat = []
+ for item in items:
+ if isinstance(item, list):
+ flat.extend(flatten(item))
+ else:
+ flat.append(item)
+ return flat
+
+print(flatten([1, [2, 3], [4, [5, [6]]], 7]))
+```
+
+```text
+[1, 2, 3, 4, 5, 6, 7]
+```
+
+The loop handles one level, and the recursive call handles whatever is inside a nested list. `extend` adds the flattened sublist's items one by one instead of adding the list itself.
+:::
+
+### 5. Search a folder tree
+
+Using the `folder` dictionary from the lesson, write `count_files(folder)` that returns the number of files at any depth, and `find(folder, name)` that returns the path to the first file or folder with that name (like `/photos/trip/khiva.jpg`), or `None` if it isn't there. Print `count_files(folder)`, `find(folder, "khiva.jpg")`, and `find(folder, "missing.txt")`.
+
+::: details Solution
+```python
+def count_files(folder):
+ count = 0
+ for child in folder.values():
+ if isinstance(child, dict):
+ count += count_files(child)
+ else:
+ count += 1
+ return count
+
+def find(folder, name, path=""):
+ for child_name, child in folder.items():
+ current = f"{path}/{child_name}"
+ if child_name == name:
+ return current
+ if isinstance(child, dict):
+ found = find(child, name, current)
+ if found:
+ return found
+ return None
+
+folder = {
+ "docs": {"plan.md": 4, "notes.txt": 2},
+ "photos": {"trip": {"bukhara.jpg": 3200, "khiva.jpg": 2900}, "cat.jpg": 800},
+ "readme.md": 1,
+}
+print(count_files(folder))
+print(find(folder, "khiva.jpg"))
+print(find(folder, "missing.txt"))
+```
+
+```text
+6
+/photos/trip/khiva.jpg
+None
+```
+
+`find` passes the path built so far **down** to each recursive call and passes the answer back **up** as soon as one call finds it. The final `return None` covers the case where nothing matched at this level.
+:::
+
+## Recap
+
+- A **recursive** function calls itself on a smaller version of the problem.
+- It needs a **base case** that returns without recursing, and a **recursive case** that moves toward it.
+- Each call waits on the **call stack** with its own local variables; results come back up level by level.
+- A missing or unreachable base case gives `RecursionError` after about 1,000 calls, so recursion suits **shallow** depth, not long sequences.
+- Use a loop for simple repetition, and recursion for data that is **nested** to an unknown depth: lists of lists, folder trees, nested dictionaries.
+
+## Further reading
+
+- [Python Tutorial - Defining functions](https://docs.python.org/3/tutorial/controlflow.html#defining-functions)
+- [`sys.getrecursionlimit()`](https://docs.python.org/3/library/sys.html#sys.getrecursionlimit)
+- [Python glossary - recursion](https://docs.python.org/3/glossary.html)
diff --git a/docs/lessons/06-functions/06-designing-functions.md b/docs/lessons/06-functions/06-designing-functions.md
new file mode 100644
index 0000000..e68f3de
--- /dev/null
+++ b/docs/lessons/06-functions/06-designing-functions.md
@@ -0,0 +1,482 @@
+---
+title: Designing Good Functions
+description: "Write functions that are easy to read, test, and reuse: one job each, clear names, logic apart from input and output, and safe refactoring."
+---
+
+# Designing Good Functions
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- What makes a function **good**: one job, a clear name, and a clear interface
+- Why you should separate **calculations** from **input and output**
+- What **pure functions** are, and why they're easy to test
+- How to spot problems like long functions, magic numbers, and flag arguments
+- How to **refactor** a messy script into clean functions, step by step
+:::
+
+## Why it matters
+
+You know **how** to write functions; now write them **well**. Two programs can print the same output, yet one is easy to change and the other is a nightmare, depending on how the code is split into functions.
+
+## 1. One function, one job
+
+A function should do **one** thing, and its name should say what that is. If you need "and" to describe it, it's probably doing too much.
+
+```python
+# Bad: reads, checks, calculates, and prints, all in one
+def process():
+ price = float(input("Price: "))
+ if price < 0:
+ print("Invalid")
+ return
+ total = price * 1.12
+ print(f"Total: {total:,.2f}")
+```
+
+```python
+# Good: each function has one job
+def add_vat(price, rate=0.12):
+ return price * (1 + rate)
+
+def format_money(amount):
+ return f"{amount:,.2f} som"
+
+print(format_money(add_vat(250000)))
+```
+
+```text
+280,000.00 som
+```
+
+Small functions are easier to name, test, and reuse. Keep the **interface** small too: a few parameters, no `True`/`False` "mode" flags (`format_name(name, True)` says nothing), and one kind of return value.
+
+## 2. Names that explain
+
+Compare `calc(x, y)` with `calculate_discount(price, percent)`:
+
+- Functions **do** things, so start with a verb: `get_`, `calculate_`, `print_`.
+- Functions that answer yes/no start with `is_`, `has_`, or `can_` and return a boolean.
+- Name parameters for what they **mean**, not their type: `price` rather than `number`.
+
+## 3. Separate logic from input and output
+
+The most useful design habit: keep **calculations** apart from `input()` and `print()`.
+
+```python
+# Logic: pure calculations, no input or print
+def bmi(weight_kg, height_m):
+ return weight_kg / height_m ** 2
+
+def bmi_category(value):
+ if value < 18.5:
+ return "underweight"
+ if value < 25:
+ return "normal"
+ return "overweight"
+
+# Input and output: talks to the user and uses the logic
+def main():
+ weight = float(input("Weight (kg): "))
+ height = float(input("Height (m): "))
+ value = bmi(weight, height)
+ print(f"BMI {value:.1f}: {bmi_category(value)}")
+
+# The logic can be checked without typing anything
+assert round(bmi(70, 1.75), 1) == 22.9
+assert bmi_category(18.5) == "normal" # boundary
+assert bmi_category(25) == "overweight" # boundary
+print("All checks passed")
+```
+
+```text
+All checks passed
+```
+
+To run it as a program, call `main()` at the bottom. *Modules and Imports* shows the standard way, `if __name__ == "__main__": main()`.
+
+The logic is **testable** without typing and **reusable** without `input()`, and `main()` reads like a summary.
+
+## 4. Prefer pure functions
+
+A **pure function**:
+
+1. returns a result that depends **only** on its arguments, and
+2. has **no side effects**: it doesn't print, read input, change globals, or modify its arguments.
+
+```python
+# Pure: same input → same output, nothing else happens
+def apply_discount(prices, percent):
+ return [p * (1 - percent / 100) for p in prices]
+
+# Impure: changes the caller's list and prints
+def apply_discount_in_place(prices, percent):
+ prices[:] = apply_discount(prices, percent)
+ print("Discount applied")
+```
+
+Programs do need side effects (printing, saving files); keep them in a few places, like `main()`, and keep the rest pure.
+
+## 5. No magic numbers
+
+A **magic number** is an unexplained value in the middle of code. In `return subtotal * 1.12 + 20000`, what are `1.12` and `20000`? Named constants answer that:
+
+```python
+VAT_RATE = 0.12
+FREE_DELIVERY_FROM = 150_000
+DELIVERY_FEE = 20_000
+
+def delivery_total(subtotal):
+ total = subtotal * (1 + VAT_RATE)
+ if subtotal < FREE_DELIVERY_FROM:
+ total += DELIVERY_FEE
+ return total
+
+print(round(delivery_total(100_000)))
+print(round(delivery_total(200_000)))
+```
+
+```text
+132000
+224000
+```
+
+Now the code explains itself, and when the delivery fee changes, you change it in **one** place.
+
+## 6. Document the contract
+
+For anything beyond a trivial function, a docstring should say **what** the function does, what it expects, and what it returns:
+
+```python
+def split_bill(total, people, tip_percent=10):
+ """Return how much each person pays, including the tip.
+
+ total: the bill before the tip
+ people: how many people share it (at least 1)
+ """
+ with_tip = total * (1 + tip_percent / 100)
+ return with_tip / people
+
+print(round(split_bill(300000, 4), 2))
+```
+
+```text
+82500.0
+```
+
+::: details Preview: type hints
+In *Type Hints* you'll learn to write the types in the signature: `def split_bill(total: float, people: int, tip_percent: float = 10) -> float:`. You don't need them yet.
+:::
+
+## Refactoring: a worked example
+
+**Refactoring** means improving the structure of code without changing what it does. Here's a typical first script:
+
+```python
+scores_text = "Aziza:92,Bekzod:67,Dilnoza:85,Farrukh:48"
+entries = scores_text.split(",")
+total = 0
+count = 0
+print("REPORT")
+print("------")
+for e in entries:
+ parts = e.split(":")
+ n = parts[0]
+ s = int(parts[1])
+ total = total + s
+ count = count + 1
+ if s >= 60:
+ print(n, s, "PASS")
+ else:
+ print(n, s, "FAIL")
+print("------")
+print("Average:", total / count)
+```
+
+Parsing, grading, and printing are tangled together. Here it is after three small steps:
+
+```python
+PASS_MARK = 60
+
+# Step 1: pull out the parsing
+def parse_scores(text):
+ result = []
+ for entry in text.split(","):
+ name, score = entry.split(":")
+ result.append((name, int(score)))
+ return result
+
+# Step 2: pull out the rules, and name the magic number
+def grade(score):
+ return "PASS" if score >= PASS_MARK else "FAIL"
+
+def average(numbers):
+ return sum(numbers) / len(numbers)
+
+# Step 3: build the report in one function that returns its lines
+def report_lines(records):
+ lines = ["REPORT", "------"]
+ for name, score in records:
+ lines.append(f"{name} {score} {grade(score)}")
+ lines.append("------")
+ lines.append(f"Average: {average([s for _, s in records])}")
+ return lines
+
+records = parse_scores("Aziza:92,Bekzod:67,Dilnoza:85,Farrukh:48")
+for line in report_lines(records):
+ print(line)
+
+# The old script printed exactly these lines
+before = [
+ "REPORT",
+ "------",
+ "Aziza 92 PASS",
+ "Bekzod 67 PASS",
+ "Dilnoza 85 PASS",
+ "Farrukh 48 FAIL",
+ "------",
+ "Average: 73.0",
+]
+assert report_lines(records) == before
+```
+
+```text
+REPORT
+------
+Aziza 92 PASS
+Bekzod 67 PASS
+Dilnoza 85 PASS
+Farrukh 48 FAIL
+------
+Average: 73.0
+```
+
+The output is identical, and the `assert` proves it: `before` holds the lines the old script printed, so a single changed character would stop the program with an `AssertionError`. Returning lines instead of printing them makes this check possible, and reading scores from a file would change only `parse_scores`.
+
+**A separate step: improve the formatting.** Only after the refactor is checked do you change what the program prints, and update `before` on purpose. For example, `f"{name:<9}{score:>4} {grade(score)}"` in `report_lines` turns the rows into aligned columns such as `Aziza 92 PASS`.
+
+::: tip Refactor safely
+Change **one thing at a time** and rerun your checks after each step. Restructure first; change the output afterwards.
+:::
+
+## Try it
+
+The function below does too much. Split it into at least three smaller functions: one for parsing, one for calculating, and one for formatting.
+
+
+
+## Common mistakes
+
+### 1. Functions that print instead of return
+
+```python
+# Bad: prints, so the result can't be used
+def average(scores):
+ print(sum(scores) / len(scores))
+
+result = average([80, 90])
+print(result)
+```
+
+```text
+85.0
+None
+```
+
+`average` shows the number but gives back `None`, so the program can't compare, store, or test it. **Fix:** `return sum(scores) / len(scores)`, and print in one place.
+
+### 2. Hidden dependencies on globals
+
+```python
+discount = 10
+
+# Bad: the result depends on a global that other code can change
+def final_price(price):
+ return price * (1 - discount / 100)
+
+print(final_price(50000))
+discount = 50 # somewhere else in the program...
+print(final_price(50000)) # same call, different answer
+```
+
+```text
+45000.0
+25000.0
+```
+
+**Fix:** pass what the function needs as an argument: `def final_price(price, discount):`.
+
+### 3. Over-splitting
+
+```py
+# Bad: tiny functions, each used once
+def get_name(entry):
+ return entry.split(":")[0]
+
+def get_score(entry):
+ return int(entry.split(":")[1])
+```
+
+Tiny functions make the reader jump around; one `parse_entry(entry)` that returns `(name, score)` is clearer. Split when a piece has a clear name and purpose, or is used in several places.
+
+## Practice
+
+### 1. Name it better
+
+Rename the function and parameters so the code explains itself.
+
+```python
+def f(a, b):
+ return a * b / 100
+
+print(f(250000, 15))
+```
+
+::: details Solution
+```python
+def percent_of(amount, percent):
+ return amount * percent / 100
+
+print(percent_of(250000, 15))
+```
+:::
+
+### 2. Remove the magic numbers
+
+```python
+def shipping_cost(weight):
+ if weight <= 2:
+ return 25000
+ return 25000 + (weight - 2) * 8000
+```
+
+::: details Solution
+```python
+BASE_WEIGHT_KG = 2
+BASE_COST = 25_000
+COST_PER_EXTRA_KG = 8_000
+
+def shipping_cost(weight_kg):
+ if weight_kg <= BASE_WEIGHT_KG:
+ return BASE_COST
+ extra_kg = weight_kg - BASE_WEIGHT_KG
+ return BASE_COST + extra_kg * COST_PER_EXTRA_KG
+
+assert shipping_cost(1) == 25000
+assert shipping_cost(5) == 49000
+print("OK")
+```
+:::
+
+### 3. Separate logic from I/O
+
+Split this into a **pure** function `convert_seconds(total)` that returns `(hours, minutes, seconds)`, and a separate part that handles input and output. Add `assert` checks for `3725` → `(1, 2, 5)` and `59` → `(0, 0, 59)`.
+
+```python
+def show_time():
+ total = int(input("Seconds: "))
+ print(total // 3600, "h", total % 3600 // 60, "min", total % 60, "s")
+```
+
+::: details Solution
+```python
+def convert_seconds(total):
+ hours, rest = divmod(total, 3600)
+ minutes, seconds = divmod(rest, 60)
+ return hours, minutes, seconds
+
+def show_time():
+ total = int(input("Seconds: "))
+ h, m, s = convert_seconds(total)
+ print(f"{h} h {m} min {s} s")
+
+assert convert_seconds(3725) == (1, 2, 5)
+assert convert_seconds(59) == (0, 0, 59)
+print("OK")
+```
+:::
+
+### 4. Replace the flag
+
+`format_name("aziza", "karimova", True)` returns `"Karimova, Aziza"`, and `False` gives `"Aziza Karimova"`. Redesign it so calls are readable without the definition.
+
+```python
+def format_name(first, last, flag):
+ if flag:
+ return f"{last.title()}, {first.title()}"
+ return f"{first.title()} {last.title()}"
+```
+
+::: details Solution
+Two clearly named functions (a keyword-only argument such as `last_name_first=True` also works):
+
+```python
+def display_name(first, last):
+ return f"{first.title()} {last.title()}"
+
+def sortable_name(first, last):
+ return f"{last.title()}, {first.title()}"
+
+print(display_name("aziza", "karimova"))
+print(sortable_name("aziza", "karimova"))
+```
+
+:::
+
+### 5. Refactor the refactor
+
+Refactor the program in **Try it** above into small functions:
+
+- `parse_order(text)` returns a list of `(name, qty, price)` tuples with numbers as `int`,
+- `order_total(items, vat_rate=0.12)` returns the total including VAT,
+- `print_order(text)` uses them to print the same output as before.
+
+Add `assert` checks for the two pure functions.
+
+::: details Solution
+```python
+VAT_RATE = 0.12
+
+def parse_order(text):
+ items = []
+ for part in text.split(";"):
+ name, qty, price = part.split(",")
+ items.append((name, int(qty), int(price)))
+ return items
+
+def order_total(items, vat_rate=VAT_RATE):
+ return sum(qty * price for _, qty, price in items) * (1 + vat_rate)
+
+def print_order(text):
+ items = parse_order(text)
+ for name, qty, price in items:
+ print(f"{name:<8}{qty:>3} x {price:>7,} = {qty * price:>9,}")
+ print(f"TOTAL: {order_total(items):,.0f} som (incl. {VAT_RATE:.0%} VAT)")
+
+assert parse_order("Tea,2,15000") == [("Tea", 2, 15000)]
+assert round(order_total([("A", 1, 100)])) == 112
+
+print_order("Tea,2,15000;Samsa,4,8000;Juice,1,12000")
+```
+
+```text
+Tea 2 x 15,000 = 30,000
+Samsa 4 x 8,000 = 32,000
+Juice 1 x 12,000 = 12,000
+TOTAL: 82,880 som (incl. 12% VAT)
+```
+:::
+
+## Recap
+
+- Give each function **one job** and a **name** that says what it does.
+- Keep **calculations** in pure functions and **input/output** in a few places like `main()`.
+- **Pure functions** have no side effects, so they're easy to test with `assert`.
+- Replace **magic numbers** with named constants, avoid mode flags, and document functions with docstrings.
+- **Refactor** in small steps, and check that the output stays the same.
+
+## Further reading
+
+- [PEP 8 - Style guide (naming conventions)](https://peps.python.org/pep-0008/#naming-conventions)
+- [PEP 257 - Docstring conventions](https://peps.python.org/pep-0257/)
+- [PEP 20 - The Zen of Python](https://peps.python.org/pep-0020/)
diff --git a/docs/lessons/06-functions/07-lambda-and-higher-order-functions.md b/docs/lessons/06-functions/07-lambda-and-higher-order-functions.md
new file mode 100644
index 0000000..180e192
--- /dev/null
+++ b/docs/lessons/06-functions/07-lambda-and-higher-order-functions.md
@@ -0,0 +1,482 @@
+---
+title: Lambdas and Higher-Order Functions
+description: "Treat functions as values: pass them to other functions, write short lambda functions, sort with custom keys, use map() and filter(), and return functions from functions."
+---
+
+# Lambdas and Higher-Order Functions
+
+{.lesson-cover width=1536 height=1024}
+
+::: tip What you'll learn
+- That functions are **values**, and what a **higher-order function** is
+- How to write small anonymous functions with `lambda`
+- How to sort, find `min`/`max`, and group with custom `key` functions
+- How `map()` and `filter()` compare with comprehensions
+- How to create functions that build other functions
+:::
+
+## Why it matters
+
+You've already written `sorted(names, key=str.lower)`: you handed a **function** to another function, and it used it for you. Instead of writing a new sorting loop for every situation, you write one small function that says *what* to compare, and reuse Python's fast, tested sorting. The same idea powers event handlers and data pipelines.
+
+## Functions are values
+
+A function name refers to a function object, just like a variable name refers to a number or string. You can assign it to another name, put it in a list, or pass it around:
+
+```python
+def shout(text):
+ return text.upper() + "!"
+
+def whisper(text):
+ return text.lower() + "..."
+
+speak = shout # no parentheses: the function itself
+print(speak("hello"))
+
+for style in [shout, whisper]:
+ print(style("Good morning"))
+```
+
+```text
+HELLO!
+GOOD MORNING!
+good morning...
+```
+
+Functions can even be values in a dictionary, which is a neat replacement for a long `if`/`elif` chain:
+
+```python
+def add(a, b):
+ return a + b
+
+def subtract(a, b):
+ return a - b
+
+operations = {"+": add, "-": subtract}
+
+print(operations["+"](10, 4))
+print(operations["-"](10, 4))
+```
+
+```text
+14
+6
+```
+
+## Higher-order functions
+
+A **higher-order function** is a function that takes another function as an argument, or returns a function. Here's one you can write yourself:
+
+```python
+def apply_to_all(func, items):
+ """Return a new list with func applied to every item."""
+ return [func(item) for item in items]
+
+def double(n):
+ return n * 2
+
+print(apply_to_all(double, [1, 2, 3]))
+print(apply_to_all(str.upper, ["a", "b"]))
+```
+
+```text
+[2, 4, 6]
+['A', 'B']
+```
+
+`apply_to_all` doesn't care what `func` does; it just calls it.
+
+## `lambda`: tiny anonymous functions
+
+Defining a whole function just to pass `double` somewhere feels heavy. A **lambda** creates a small function in a single expression:
+
+```text
+lambda parameters: expression
+```
+
+```python
+double = lambda n: n * 2 # the same as def double(n): return n * 2
+print(double(21))
+
+add = lambda a, b: a + b
+print(add(3, 4))
+```
+
+```text
+42
+7
+```
+
+Rules of a lambda:
+
+- It can contain only **one expression**, whose value is returned automatically. No `return` keyword, and no statements like `if` blocks, loops, or assignments.
+- It has no name of its own, which is why it's called **anonymous**.
+
+Assigning a lambda to a name, as above, is legal but discouraged by PEP 8; the examples above do it only to compare with `def`. If it deserves a name, use `def`. Lambdas are meant to be written **directly where they're used**, as arguments:
+
+```py
+print(apply_to_all(lambda n: n ** 2, [1, 2, 3]))
+```
+
+```text
+[1, 4, 9]
+```
+
+A conditional expression works inside a lambda, written right where it's used:
+
+```python
+print(list(map(lambda score: "pass" if score >= 60 else "fail", [75, 40])))
+```
+
+```text
+['pass', 'fail']
+```
+
+## Sorting with `key`
+
+This is where you'll use lambdas the most. The `key` function receives **one item** and returns the value to sort by:
+
+```python
+students = [
+ {"name": "Aziza", "age": 20, "score": 92},
+ {"name": "Bekzod", "age": 22, "score": 85},
+ {"name": "Dilnoza", "age": 19, "score": 97},
+]
+
+by_age = sorted(students, key=lambda s: s["age"])
+by_score = sorted(students, key=lambda s: s["score"], reverse=True)
+
+print([s["name"] for s in by_age])
+print([s["name"] for s in by_score])
+```
+
+```text
+['Dilnoza', 'Aziza', 'Bekzod']
+['Dilnoza', 'Aziza', 'Bekzod']
+```
+
+More key examples:
+
+```python
+products = [("Tea", 15000), ("Coffee", 45000), ("Juice", 12000)]
+words = ["banana", "Apple", "cherry", "fig"]
+
+print(sorted(products, key=lambda p: p[1])) # by price
+print(sorted(words, key=lambda w: w.lower())) # ignoring case
+print(sorted(words, key=lambda w: (len(w), w.lower()))) # by length, then alphabetically
+```
+
+```text
+[('Juice', 12000), ('Tea', 15000), ('Coffee', 45000)]
+['Apple', 'banana', 'cherry', 'fig']
+['fig', 'Apple', 'banana', 'cherry']
+```
+
+Returning a **tuple** from the key sorts by several criteria: first by the first value, and ties by the second. To reverse one numeric criterion, negate it: `key=lambda s: (-s["score"], s["name"])`.
+
+`min()` and `max()` accept the same `key`:
+
+```python
+students = [
+ {"name": "Aziza", "score": 92},
+ {"name": "Bekzod", "score": 85},
+]
+
+best = max(students, key=lambda s: s["score"])
+print(best["name"])
+```
+
+```text
+Aziza
+```
+
+## `map()` and `filter()`
+
+Two classic higher-order functions:
+
+- `map(func, items)` applies `func` to every item.
+- `filter(func, items)` keeps the items for which `func` returns a truthy value.
+
+Both return lazy iterators: printing one shows only `