diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8ccb95c..feeb738 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,8 +1,12 @@ name: CI +# dev is the working branch: every push to it is checked. +# A pull request into main is the gate before publishing. on: - pull_request: + push: branches: [dev] + pull_request: + branches: [main] workflow_dispatch: permissions: @@ -30,7 +34,10 @@ jobs: env: PYTHON: python MPLBACKEND: Agg - run: python scripts/check-examples.py + run: python scripts/examples.py --twice + + - name: Check lessons against the template + run: python scripts/lint.py - run: npm ci diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 6cf5c8c..70fbfa7 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -1,7 +1,7 @@ name: Deploy to GitHub Pages -# main only holds the repo files (LICENSE, .gitignore, workflows); the site lives on dev. -# Run manually from Actions -> Deploy to GitHub Pages -> Run workflow, and pick the dev branch. +# Publishing is manual: Actions -> Deploy to GitHub Pages -> Run workflow, then pick the +# branch to publish (main after a merge, or dev to preview work in progress). on: workflow_dispatch: @@ -45,7 +45,7 @@ jobs: env: PYTHON: python MPLBACKEND: Agg - run: python scripts/check-examples.py + run: python scripts/examples.py - run: npm ci diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 0f06aab..ad043a5 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -21,7 +21,7 @@ permissions: id-token: write concurrency: - group: release-pages + group: pages cancel-in-progress: false jobs: @@ -37,7 +37,7 @@ jobs: env: VERSION: ${{ inputs.version }} run: | - python - <<'PY' + python3 - <<'PY' import os, re, sys version = os.environ["VERSION"] pattern = r"\d+\.\d+\.\d+(?:-(?:alpha|beta|rc)\.\d+)?" @@ -122,7 +122,7 @@ jobs: env: PYTHON: python MPLBACKEND: Agg - run: python scripts/check-examples.py + run: python scripts/examples.py - run: npm ci diff --git a/.gitignore b/.gitignore index e0263aa..c2124c9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,229 +1,19 @@ -# Byte-compiled / optimized / DLL files -__pycache__/ -*.py[codz] -*$py.class - -# C extensions -*.so - -# Distribution / packaging -.Python -build/ -develop-eggs/ +# Node and VitePress +node_modules/ dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -wheels/ -share/python-wheels/ -*.egg-info/ -.installed.cfg -*.egg -MANIFEST - -# PyInstaller -# Usually these files are written by a python script from a template -# before PyInstaller builds the exe, so as to inject date/other infos into it. -*.manifest -*.spec - -# Installer logs -pip-log.txt -pip-delete-this-directory.txt - -# Unit test / coverage reports -htmlcov/ -.tox/ -.nox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*.cover -*.py.cover -.hypothesis/ -.pytest_cache/ -cover/ - -# Translations -*.mo -*.pot - -# Django stuff: -*.log -local_settings.py -db.sqlite3 -db.sqlite3-journal - -# Flask stuff: -instance/ -.webassets-cache - -# Scrapy stuff: -.scrapy - -# Sphinx documentation -docs/_build/ - -# PyBuilder -.pybuilder/ -target/ - -# Jupyter Notebook -.ipynb_checkpoints - -# IPython -profile_default/ -ipython_config.py - -# pyenv -# For a library or package, you might want to ignore these files since the code is -# intended to run in multiple environments; otherwise, check them in: -# .python-version - -# pipenv -# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. -# However, in case of collaboration, if having platform-specific dependencies or dependencies -# having no cross-platform support, pipenv may install dependencies that don't work, or not -# install all needed dependencies. -# Pipfile.lock - -# UV -# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. -# This is especially recommended for binary packages to ensure reproducibility, and is more -# commonly ignored for libraries. -# uv.lock - -# poetry -# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. -# This is especially recommended for binary packages to ensure reproducibility, and is more -# commonly ignored for libraries. -# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control -# poetry.lock -# poetry.toml - -# pdm -# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. -# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python. -# https://pdm-project.org/en/latest/usage/project/#working-with-version-control -# pdm.lock -# pdm.toml -.pdm-python -.pdm-build/ - -# pixi -# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control. -# pixi.lock -# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one -# in the .venv directory. It is recommended not to include this directory in version control. -.pixi - -# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm -__pypackages__/ - -# Celery stuff -celerybeat-schedule -celerybeat.pid - -# Redis -*.rdb -*.aof -*.pid - -# RabbitMQ -mnesia/ -rabbitmq/ -rabbitmq-data/ - -# ActiveMQ -activemq-data/ +docs/.vitepress/cache/ -# SageMath parsed files -*.sage.py +# Generated into the site (see scripts/copy-runtime.mjs and scripts/build-lab.sh) +docs/public/pyodide/ +docs/public/lab/ +build/ +.jupyterlite.doit.db -# Environments -.env -.envrc -.venv -env/ +# Python +__pycache__/ +*.py[cod] +.venv/ venv/ -ENV/ -env.bak/ -venv.bak/ - -# Spyder project settings -.spyderproject -.spyproject - -# Rope project settings -.ropeproject - -# mkdocs documentation -/site - -# mypy -.mypy_cache/ -.dmypy.json -dmypy.json - -# Pyre type checker -.pyre/ - -# pytype static type analyzer -.pytype/ - -# Cython debug symbols -cython_debug/ - -# PyCharm -# JetBrains specific template is maintained in a separate JetBrains.gitignore that can -# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore -# and can be added to the global gitignore or merged into this file. For a more nuclear -# option (not recommended) you can uncomment the following to ignore the entire idea folder. -# .idea/ -# Abstra -# Abstra is an AI-powered process automation framework. -# Ignore directories containing user credentials, local state, and settings. -# Learn more at https://abstra.io/docs -.abstra/ - -# Visual Studio Code -# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore -# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore -# and can be added to the global gitignore or merged into this file. However, if you prefer, -# you could uncomment the following to ignore the entire vscode folder -# .vscode/ -# Temporary file for partial code execution -tempCodeRunnerFile.py - -# Ruff stuff: -.ruff_cache/ - -# PyPI configuration file -.pypirc - -# Marimo -marimo/_static/ -marimo/_lsp/ -__marimo__/ - -# Streamlit -.streamlit/secrets.toml - -# python.uz site -node_modules/ -docs/.vitepress/cache/ -.sites-runtime/ -dist/ -docs/public/pyodide/ -build/ -docs/public/lab/ +# OS .DS_Store -.jupyterlite.doit.db diff --git a/README.md b/README.md new file mode 100644 index 0000000..8926989 --- /dev/null +++ b/README.md @@ -0,0 +1,52 @@ +# Python Tutorials + +A free Python course in **English** and **Uzbek**, from your first `print()` to decorators and async. Examples run in the browser, exercises are checked on the page, and nothing needs to be installed. + +**Live site:** [yakhyo.github.io/python-tutorials](https://yakhyo.github.io/python-tutorials/) · [Uzbek version](https://yakhyo.github.io/python-tutorials/uz/) + +> Pythonni noldan örganmoqçimisiz? Kurs toʻliq özbek tilida ham bor: [özbekça versiya](https://yakhyo.github.io/python-tutorials/uz/). + +## What's inside + +82 lessons in 14 modules, written for Python 3.14. Every lesson has runnable examples, common mistakes with real error output, and five exercises with solutions. Every module ends with a quiz. + +| Part | Modules | +| --- | --- | +| **Foundations** | [Getting Started](docs/lessons/01-getting-started) · [Values and Variables](docs/lessons/02-values-and-variables) · [Decisions](docs/lessons/03-making-decisions) · [Loops](docs/lessons/04-loops) · [Collections](docs/lessons/05-collections) · [Functions](docs/lessons/06-functions) | +| **Real Programs** | [Standard Library](docs/lessons/07-modules-and-the-standard-library) · [Errors and Files](docs/lessons/08-errors-and-files) · [Classes](docs/lessons/09-classes-and-objects) · [Object-Oriented Design](docs/lessons/10-object-oriented-design) · [Testing](docs/lessons/11-testing-and-debugging) · [Generators and Regex](docs/lessons/12-going-further) · [Data with pandas](docs/lessons/13-working-with-data) *(optional)* | +| **Advanced** *(optional)* | [Decorators, the data model, context managers, async, performance, design patterns and concurrency](docs/lessons/14-advanced-python) | + +Seven guided projects along the way: a number guessing game, quiz game, expense tracker, library system, text analyzer, sales report and log pipeline. + +The course is complete in both languages. Corrections from a full technical review are in progress. + +## Run locally + +Requires Node.js 22+ (and Python 3.10+ for the Python Lab). + +```sh +npm ci +npm run dev # http://127.0.0.1:5173 +npm run build # build the static site into dist/ +``` + +Set `SKIP_LAB=1` to skip building the JupyterLite lab. + +## Check changes + +```sh +python3 scripts/examples.py --twice # run every code example with Python 3.14 +python3 scripts/lint.py # check lessons against the template +``` + +## Contributing lessons + +Add the lesson to `docs/.vitepress/course.json`, then run `python3 scripts/organize-lessons.py` to place the file. Use `docs/lessons/05-collections/04-dictionaries.md` as the reference lesson, and mirror every change in the Uzbek lesson under `docs/uz/darslar/`. + +## Deployment + +Work happens on `dev`. CI runs on pull requests into `dev`. Deploys and releases to GitHub Pages run manually from the Actions tab. + +## License + +[MIT](LICENSE) © 2026 Yakhyokhuja Valikhujaev diff --git a/docs/.vitepress/config.mjs b/docs/.vitepress/config.mjs new file mode 100644 index 0000000..29879e5 --- /dev/null +++ b/docs/.vitepress/config.mjs @@ -0,0 +1,187 @@ +import { defineConfig } from 'vitepress' +import { readFileSync, existsSync } from 'node:fs' +import catppuccinLatte from '@shikijs/themes/catppuccin-latte' +import catppuccinMocha from '@shikijs/themes/catppuccin-mocha' + +// Catppuccin is drawn for its own background, not VitePress's, so several token colors land +// under the WCAG AA 4.5:1 contrast ratio on our code background (Latte comments reach only +// 2.4:1). Scale each failing color's luminance until it passes; multiplying the linear RGB +// channels keeps the hue, so the palette still looks like Catppuccin. +const channels = hex => [1, 3, 5].map(i => parseInt(hex.slice(i, i + 2), 16) / 255) + .map(c => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4)) +const luminance = ([r, g, b]) => 0.2126 * r + 0.7152 * g + 0.0722 * b +const toHex = rgb => '#' + rgb.map(c => { + const srgb = c <= 0.0031308 ? c * 12.92 : 1.055 * c ** (1 / 2.4) - 0.055 + return Math.round(Math.min(1, Math.max(0, srgb)) * 255).toString(16).padStart(2, '0') +}).join('') +const ratio = (a, b) => { + const [hi, lo] = [luminance(channels(a)), luminance(channels(b))].sort((x, y) => y - x) + return (hi + 0.05) / (lo + 0.05) +} +const readable = (color, background, min = 4.6) => { + if (ratio(color, background) >= min) return color + const backgroundLuminance = luminance(channels(background)) + const target = backgroundLuminance > 0.5 + ? (backgroundLuminance + 0.05) / min - 0.05 + : min * (backgroundLuminance + 0.05) - 0.05 + const rgb = channels(color) + const scaled = toHex(rgb.map(c => c * (target / luminance(rgb)))) + if (ratio(scaled, background) >= min - 0.1) return scaled + // Scaling up can clip a channel; mix toward white instead. + for (let t = 0.02; t <= 1; t += 0.02) { + const mixed = toHex(rgb.map(c => c + (1 - c) * t)) + if (ratio(mixed, background) >= min) return mixed + } + return color +} +const contrastSafe = (theme, background) => ({ + ...theme, + tokenColors: theme.tokenColors.map(token => { + const foreground = token.settings?.foreground + if (!/^#[0-9a-f]{6}$/i.test(foreground || '')) return token + return { ...token, settings: { ...token.settings, foreground: readable(foreground, background) } } + }) +}) +// --vp-code-block-bg in each mode. +const codeThemes = { + light: contrastSafe(catppuccinLatte, '#f6f6f7'), + dark: contrastSafe(catppuccinMocha, '#161618') +} + +const load = file => JSON.parse(readFileSync(new URL(file, import.meta.url))) +const groupsOf = list => [...new Set(list.map(lesson => lesson.group))] + +// Lesson files live in numbered module folders so they sort in course order, +// e.g. lessons/06-functions/01-defining-functions.md. `rewrites` below keeps the +// URLs short (/lessons/defining-functions). scripts/organize-lessons.py moves the files. +const moduleFolder = group => { + const [number, name] = group.split(' · ') + return `${number}-${name.replace(/\(.*?\)/g, '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')}` +} +const lessonFiles = list => { + const counters = {} + return Object.fromEntries(list.map(({ slug, group }) => { + const folder = moduleFolder(group) + counters[folder] = (counters[folder] || 0) + 1 + return [slug, `${folder}/${String(counters[folder]).padStart(2, '0')}-${slug}.md`] + })) +} + +// English (root locale). +const courseEn = load('./course.json') +const files = lessonFiles(courseEn) +const hasQuiz = number => existsSync(new URL(`./quizzes/module-${number}.json`, import.meta.url)) +const sidebarEn = [ + { text: 'Start Here', items: [{ text: 'Course Overview', link: '/' }, { text: 'Playground', link: '/playground' }, { text: 'Python Lab (notebooks)', link: '/lab' }] }, + ...groupsOf(courseEn).map(text => { + const lessons = courseEn.filter(l => l.group === text) + const number = text.slice(0, 2) + const items = lessons.map(l => ({ text: l.title, link: `/lessons/${l.slug}` })) + if (hasQuiz(number)) items.push({ text: 'Checkpoint quiz', link: `/checkpoints/module-${number}` }) + return { text, collapsed: number !== '01', items } + }) +] + +// Uzbek (/uz/ locale): the same course, translated. Titles come from course-uz.json. +const courseUz = load('./course-uz.json') +const hasQuizUz = number => existsSync(new URL(`../uz/nazorat/module-${number}.md`, import.meta.url)) +const sidebarUz = [ + { text: 'Boşlaş', items: [{ text: 'Darslik haqida', link: '/uz/' }, { text: 'Sinov maydonçasi', link: '/uz/sinov-maydoni' }, { text: 'Python laboratoriyasi', link: '/uz/laboratoriya' }] }, + ...groupsOf(courseUz).map(text => { + const lessons = courseUz.filter(l => l.group === text) + const number = text.slice(0, 2) + const items = lessons.map(l => ({ text: l.title, link: `/uz/darslar/${l.slug}` })) + if (hasQuizUz(number)) items.push({ text: 'Nazorat testi', link: `/uz/nazorat/module-${number}` }) + return { text, collapsed: number !== '01', items } + }) +] + +// Markdown plugin: an italic lesson title (for example *Nested Data* or *Içma-iç maʼlumotlar*) +// becomes a link to that lesson, so lessons can reference each other without hard-coded links. +const linkSets = [ + { test: path => path.startsWith('lessons/') || path.startsWith('checkpoints/') || path === 'index.md', prefix: '/lessons/', dir: 'lessons/', titles: new Map(courseEn.map(l => [l.title, `/lessons/${l.slug}`])) }, + { test: path => path.startsWith('uz/'), prefix: '/uz/darslar/', dir: 'uz/darslar/', titles: new Map(courseUz.map(l => [l.title, `/uz/darslar/${l.slug}`])) } +] +function linkLessonTitles(md) { + md.core.ruler.push('lesson_title_links', state => { + const path = state.env?.relativePath || '' + const set = linkSets.find(s => s.test(path)) + if (!set) return + const current = path.startsWith(set.dir) ? `${set.prefix}${path.slice(set.dir.length).replace(/\.md$/, '')}` : '' + for (const block of state.tokens) { + if (block.type !== 'inline' || !block.children) continue + const children = block.children + for (let i = 0; i + 2 < children.length; i++) { + const [open, text, close] = [children[i], children[i + 1], children[i + 2]] + if (open.type !== 'em_open' || text.type !== 'text' || close.type !== 'em_close') continue + const href = set.titles.get(text.content) + if (!href || href === current) continue + const linkOpen = new state.Token('link_open', 'a', 1) + linkOpen.attrs = [['href', href]] + const linkClose = new state.Token('link_close', 'a', -1) + children.splice(i + 1, 0, linkOpen) + children.splice(i + 3, 0, linkClose) + i += 4 + } + } + }) +} + +const base = process.env.SITE_BASE || '/' + +const rewrites = Object.fromEntries(Object.entries(files).flatMap(([slug, file]) => [ + [`lessons/${file}`, `lessons/${slug}.md`], + [`uz/darslar/${file}`, `uz/darslar/${slug}.md`] +])) + +export default defineConfig({ + title: 'python.uz', + base, outDir: '../dist', + sitemap: { hostname: 'https://yakhyo.github.io/python-tutorials/' }, + lastUpdated: true, + rewrites, + // Catppuccin Latte/Mocha, contrast-corrected above; the CodeMirror editor matches (--cm-* in theme/style.css). + markdown: { theme: codeThemes, config: md => linkLessonTitles(md) }, + // The Python Lab (JupyterLite) is built separately into dist/lab by scripts/build-lab.sh. + ignoreDeadLinks: [/^\/lab\//], + head: [ + ['link', { rel: 'icon', href: `${base}favicon.svg` }], + ['link', { rel: 'preconnect', href: 'https://fonts.googleapis.com' }], + ['link', { rel: 'preconnect', href: 'https://fonts.gstatic.com', crossorigin: '' }], + ['link', { rel: 'stylesheet', href: 'https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&display=swap' }] + ], + locales: { + root: { + label: 'English', lang: 'en', + description: 'Learn Python from scratch with clear explanations, runnable examples, and exercises.', + themeConfig: { + nav: [{ text: 'Lessons', link: `/lessons/${courseEn[0].slug}` }, { text: 'Playground', link: '/playground' }, { text: 'Lab', link: '/lab' }], + sidebar: sidebarEn, + outline: { label: 'On this page', level: [2, 3] }, + docFooter: { prev: 'Previous lesson', next: 'Next lesson' }, + editLink: { pattern: 'https://github.com/yakhyo/python-tutorials/edit/dev/docs/:path', text: 'Suggest a change to this lesson' }, + lastUpdatedText: 'Last updated' + } + }, + uz: { + label: 'Özbekça', lang: 'uz', link: '/uz/', + description: 'Pythonni noldan örganing: tuşunarli izohlar, brauzerda işlaydigan misollar va maşqlar.', + themeConfig: { + nav: [{ text: 'Darslar', link: '/uz/darslar/what-is-python' }, { text: 'Sinov maydonçasi', link: '/uz/sinov-maydoni' }, { text: 'Laboratoriya', link: '/uz/laboratoriya' }], + sidebar: sidebarUz, + outline: { label: 'Bu sahifada', level: [2, 3] }, + docFooter: { prev: 'Oldingi dars', next: 'Keyingi dars' }, + darkModeSwitchLabel: 'Rang rejimi', sidebarMenuLabel: 'Mundarija', returnToTopLabel: 'Yuqoriga', langMenuLabel: 'Tilni özgartiriş', + editLink: { pattern: 'https://github.com/yakhyo/python-tutorials/edit/dev/docs/:path', text: 'Bu darsga özgartiriş taklif qiliş' }, + lastUpdatedText: 'Oxirgi yangilanish', notFound: { title: 'Sahifa topilmadi', quote: 'Bu manzilda sahifa yöq. Balki u köçirilgandir.', linkText: 'Boş sahifaga' } + } + } + }, + themeConfig: { + // The official Python logo (unaltered, from python.org/community/logos) next to the site name. + logo: { src: '/python-logo.svg', alt: 'Python' }, + siteTitle: false, + socialLinks: [{ icon: 'github', link: 'https://github.com/yakhyo/python-tutorials', ariaLabel: 'GitHub' }], + search: { provider: 'local', options: { locales: { uz: { translations: { button: { buttonText: 'Qidiriş', buttonAriaLabel: 'Darslardan qidiriş' }, modal: { noResultsText: 'Natija topilmadi', resetButtonTitle: 'Tozalaş', footer: { selectText: 'tanlaş', navigateText: 'ötiş', closeText: 'yopiş' } } } } } } } + } +}) diff --git a/docs/.vitepress/course-uz.json b/docs/.vitepress/course-uz.json new file mode 100644 index 0000000..27b3e59 --- /dev/null +++ b/docs/.vitepress/course-uz.json @@ -0,0 +1,412 @@ +[ + { + "slug": "what-is-python", + "title": "Python nima?", + "group": "01 · Kiriş" + }, + { + "slug": "install-and-setup", + "title": "Pythonni örnatiş", + "group": "01 · Kiriş" + }, + { + "slug": "running-python", + "title": "Python kodini işga tuşiriş", + "group": "01 · Kiriş" + }, + { + "slug": "hello-world", + "title": "Salom, dunyo!", + "group": "01 · Kiriş" + }, + { + "slug": "comments-and-style", + "title": "Izohlar va kod uslubi", + "group": "01 · Kiriş" + }, + { + "slug": "variables", + "title": "Özgaruvçilar", + "group": "02 · Özgaruvçilar va maʼlumot turlari" + }, + { + "slug": "numbers-and-math", + "title": "Sonlar va matematika", + "group": "02 · Özgaruvçilar va maʼlumot turlari" + }, + { + "slug": "strings-basics", + "title": "Satrlar", + "group": "02 · Özgaruvçilar va maʼlumot turlari" + }, + { + "slug": "string-methods-and-slicing", + "title": "Satr metodlari va kesimlar", + "group": "02 · Özgaruvçilar va maʼlumot turlari" + }, + { + "slug": "f-strings", + "title": "F-satrlar", + "group": "02 · Özgaruvçilar va maʼlumot turlari" + }, + { + "slug": "type-conversion-and-input", + "title": "Kiritiş va turlarni özgartiriş", + "group": "02 · Özgaruvçilar va maʼlumot turlari" + }, + { + "slug": "reading-errors-and-debugging", + "title": "Xato xabarlarini öqiş va tuzatiş", + "group": "02 · Özgaruvçilar va maʼlumot turlari" + }, + { + "slug": "booleans-and-comparisons", + "title": "Mantiqiy qiymatlar va taqqoslaş", + "group": "03 · Şart operatorlari" + }, + { + "slug": "if-elif-else", + "title": "if, elif va else", + "group": "03 · Şart operatorlari" + }, + { + "slug": "logical-operators", + "title": "Mantiqiy operatorlar", + "group": "03 · Şart operatorlari" + }, + { + "slug": "match-statement", + "title": "match operatori", + "group": "03 · Şart operatorlari" + }, + { + "slug": "while-loops", + "title": "while sikli", + "group": "04 · Sikllar" + }, + { + "slug": "for-loops-and-range", + "title": "for sikli va range()", + "group": "04 · Sikllar" + }, + { + "slug": "break-continue-else", + "title": "break, continue va else", + "group": "04 · Sikllar" + }, + { + "slug": "loop-patterns", + "title": "Sikllarda köp işlatiladigan usullar", + "group": "04 · Sikllar" + }, + { + "slug": "number-guessing-game", + "title": "Loyiha: Sonni topiş öyini", + "group": "04 · Sikllar" + }, + { + "slug": "lists", + "title": "Röyxatlar", + "group": "05 · Kolleksiyalar" + }, + { + "slug": "list-operations-and-sorting", + "title": "Röyxatlar bilan işlaş va saralaş", + "group": "05 · Kolleksiyalar" + }, + { + "slug": "tuples-and-unpacking", + "title": "Kortejlar va qiymatlarni ajratiş", + "group": "05 · Kolleksiyalar" + }, + { + "slug": "dictionaries", + "title": "Luğatlar", + "group": "05 · Kolleksiyalar" + }, + { + "slug": "sets", + "title": "Töplamlar", + "group": "05 · Kolleksiyalar" + }, + { + "slug": "nested-data", + "title": "Içma-iç maʼlumotlar", + "group": "05 · Kolleksiyalar" + }, + { + "slug": "comprehensions", + "title": "Comprehension ifodalari", + "group": "05 · Kolleksiyalar" + }, + { + "slug": "defining-functions", + "title": "Funksiya yaratiş", + "group": "06 · Funksiyalar" + }, + { + "slug": "parameters-and-arguments", + "title": "Parametrlar va argumentlar", + "group": "06 · Funksiyalar" + }, + { + "slug": "return-values", + "title": "Qaytariladigan qiymatlar", + "group": "06 · Funksiyalar" + }, + { + "slug": "scope", + "title": "Özgaruvçilarning köriniş sohasi", + "group": "06 · Funksiyalar" + }, + { + "slug": "recursion", + "title": "Rekursiya", + "group": "06 · Funksiyalar" + }, + { + "slug": "designing-functions", + "title": "Funksiyalarni töğri loyihalaş", + "group": "06 · Funksiyalar" + }, + { + "slug": "lambda-and-higher-order-functions", + "title": "Lambda va yuqori tartibli funksiyalar", + "group": "06 · Funksiyalar" + }, + { + "slug": "quiz-game", + "title": "Loyiha: Viktorina öyini", + "group": "06 · Funksiyalar" + }, + { + "slug": "modules-and-imports", + "title": "Modullar va import", + "group": "07 · Modullar va standart kutubxona" + }, + { + "slug": "math-random-statistics", + "title": "math, random va statistics", + "group": "07 · Modullar va standart kutubxona" + }, + { + "slug": "dates-and-times", + "title": "Sana va vaqt", + "group": "07 · Modullar va standart kutubxona" + }, + { + "slug": "collections-and-itertools", + "title": "collections va itertools", + "group": "07 · Modullar va standart kutubxona" + }, + { + "slug": "exceptions", + "title": "Istisnolarni qayta işlaş", + "group": "08 · Xatolar va fayllar" + }, + { + "slug": "raising-and-custom-exceptions", + "title": "Istisno çaqiriş va maxsus istisnolar", + "group": "08 · Xatolar va fayllar" + }, + { + "slug": "input-validation", + "title": "Kiritilgan maʼlumotni tekşiriş", + "group": "08 · Xatolar va fayllar" + }, + { + "slug": "files-and-pathlib", + "title": "Fayllar va pathlib", + "group": "08 · Xatolar va fayllar" + }, + { + "slug": "csv", + "title": "CSV bilan işlaş", + "group": "08 · Xatolar va fayllar" + }, + { + "slug": "json", + "title": "JSON bilan işlaş", + "group": "08 · Xatolar va fayllar" + }, + { + "slug": "context-managers-basics", + "title": "with operatori", + "group": "08 · Xatolar va fayllar" + }, + { + "slug": "expense-tracker", + "title": "Loyiha: Xarajatlar daftari", + "group": "08 · Xatolar va fayllar" + }, + { + "slug": "why-oop", + "title": "Obyektga yönaltirilgan dasturlaş nima uçun kerak?", + "group": "09 · Klasslar va obyektlar" + }, + { + "slug": "classes-and-objects", + "title": "Klasslar va obyektlar", + "group": "09 · Klasslar va obyektlar" + }, + { + "slug": "methods-and-attributes", + "title": "Metodlar va obyekt holati", + "group": "09 · Klasslar va obyektlar" + }, + { + "slug": "class-attributes-and-methods", + "title": "Klass atributlari, klass metodlari va statik metodlar", + "group": "09 · Klasslar va obyektlar" + }, + { + "slug": "properties-and-encapsulation", + "title": "Xossalar va inkapsulyatsiya", + "group": "09 · Klasslar va obyektlar" + }, + { + "slug": "special-methods", + "title": "Obyektlarni ifodalaş va taqqoslaş", + "group": "09 · Klasslar va obyektlar" + }, + { + "slug": "operators-and-containers", + "title": "Operatorlar va konteynerlar", + "group": "09 · Klasslar va obyektlar" + }, + { + "slug": "inheritance", + "title": "Vorislik va super()", + "group": "10 · Obyektga yönaltirilgan loyihalaş" + }, + { + "slug": "polymorphism-and-abcs", + "title": "Polimorfizm, duck typing va abstrakt klasslar", + "group": "10 · Obyektga yönaltirilgan loyihalaş" + }, + { + "slug": "composition", + "title": "Kompozitsiya yoki vorislik?", + "group": "10 · Obyektga yönaltirilgan loyihalaş" + }, + { + "slug": "dataclasses", + "title": "Dataclasslar", + "group": "10 · Obyektga yönaltirilgan loyihalaş" + }, + { + "slug": "enums", + "title": "Enum turlari", + "group": "10 · Obyektga yönaltirilgan loyihalaş" + }, + { + "slug": "type-hints", + "title": "Type hintlar", + "group": "10 · Obyektga yönaltirilgan loyihalaş" + }, + { + "slug": "oop-project", + "title": "Loyiha: Kutubxona boşqaruv tizimi", + "group": "10 · Obyektga yönaltirilgan loyihalaş" + }, + { + "slug": "testing-with-assert", + "title": "assert bilan testlaş", + "group": "11 · Testlaş va xatolarni tuzatiş" + }, + { + "slug": "choosing-test-cases", + "title": "Test holatlarini tanlaş", + "group": "11 · Testlaş va xatolarni tuzatiş" + }, + { + "slug": "pytest-basics", + "title": "pytest bilan testlaş", + "group": "11 · Testlaş va xatolarni tuzatiş" + }, + { + "slug": "debugging-and-logging", + "title": "Xatolarni tuzatiş va logging", + "group": "11 · Testlaş va xatolarni tuzatiş" + }, + { + "slug": "iterators-and-generators", + "title": "Iteratorlar va generatorlar", + "group": "12 · Keyingi qadamlar" + }, + { + "slug": "regular-expressions", + "title": "Regulyar ifodalar", + "group": "12 · Keyingi qadamlar" + }, + { + "slug": "text-processing-project", + "title": "Loyiha: Matn tahlilçisi", + "group": "12 · Keyingi qadamlar" + }, + { + "slug": "reading-data", + "title": "Maʼlumot fayllarini öqiş", + "group": "13 · Maʼlumotlar bilan işlaş (ixtiyoriy)" + }, + { + "slug": "pandas-basics", + "title": "pandas asoslari", + "group": "13 · Maʼlumotlar bilan işlaş (ixtiyoriy)" + }, + { + "slug": "charts-with-matplotlib", + "title": "matplotlib bilan grafiklar", + "group": "13 · Maʼlumotlar bilan işlaş (ixtiyoriy)" + }, + { + "slug": "data-report-project", + "title": "Loyiha: Savdo hisoboti", + "group": "13 · Maʼlumotlar bilan işlaş (ixtiyoriy)" + }, + { + "slug": "closures-and-decorators", + "title": "Closure va dekoratorlar", + "group": "14 · Advanced Python (ixtiyoriy)" + }, + { + "slug": "python-data-model", + "title": "Python maʼlumot modeli", + "group": "14 · Advanced Python (ixtiyoriy)" + }, + { + "slug": "context-managers-in-depth", + "title": "Kontekst menejerlarini çuqurroq örganiş", + "group": "14 · Advanced Python (ixtiyoriy)" + }, + { + "slug": "async-await", + "title": "Async va await", + "group": "14 · Advanced Python (ixtiyoriy)" + }, + { + "slug": "memory-and-performance", + "title": "Xotira va samaradorlik", + "group": "14 · Advanced Python (ixtiyoriy)" + }, + { + "slug": "design-patterns", + "title": "Pythonça dizayn patternlar", + "group": "14 · Advanced Python (ixtiyoriy)" + }, + { + "slug": "threads-and-processes", + "title": "Oqimlar va jarayonlar", + "group": "14 · Advanced Python (ixtiyoriy)" + }, + { + "slug": "testing-in-depth", + "title": "Testlaşni çuqurroq örganiş", + "group": "14 · Advanced Python (ixtiyoriy)" + }, + { + "slug": "advanced-project", + "title": "Loyiha: Log konveyeri", + "group": "14 · Advanced Python (ixtiyoriy)" + } +] diff --git a/docs/.vitepress/course.json b/docs/.vitepress/course.json new file mode 100644 index 0000000..cea21eb --- /dev/null +++ b/docs/.vitepress/course.json @@ -0,0 +1,412 @@ +[ + { + "slug": "what-is-python", + "title": "What Is Python?", + "group": "01 · Getting Started" + }, + { + "slug": "install-and-setup", + "title": "Installing Python", + "group": "01 · Getting Started" + }, + { + "slug": "running-python", + "title": "Running Python Code", + "group": "01 · Getting Started" + }, + { + "slug": "hello-world", + "title": "Hello, World!", + "group": "01 · Getting Started" + }, + { + "slug": "comments-and-style", + "title": "Comments and Code Style", + "group": "01 · Getting Started" + }, + { + "slug": "variables", + "title": "Variables", + "group": "02 · Values and Variables" + }, + { + "slug": "numbers-and-math", + "title": "Numbers and Math", + "group": "02 · Values and Variables" + }, + { + "slug": "strings-basics", + "title": "Strings", + "group": "02 · Values and Variables" + }, + { + "slug": "string-methods-and-slicing", + "title": "String Methods and Slicing", + "group": "02 · Values and Variables" + }, + { + "slug": "f-strings", + "title": "F-Strings", + "group": "02 · Values and Variables" + }, + { + "slug": "type-conversion-and-input", + "title": "Input and Type Conversion", + "group": "02 · Values and Variables" + }, + { + "slug": "reading-errors-and-debugging", + "title": "Reading Errors and Debugging", + "group": "02 · Values and Variables" + }, + { + "slug": "booleans-and-comparisons", + "title": "Booleans and Comparisons", + "group": "03 · Making Decisions" + }, + { + "slug": "if-elif-else", + "title": "if, elif, and else", + "group": "03 · Making Decisions" + }, + { + "slug": "logical-operators", + "title": "Logical Operators", + "group": "03 · Making Decisions" + }, + { + "slug": "match-statement", + "title": "The match Statement", + "group": "03 · Making Decisions" + }, + { + "slug": "while-loops", + "title": "while Loops", + "group": "04 · Loops" + }, + { + "slug": "for-loops-and-range", + "title": "for Loops and range()", + "group": "04 · Loops" + }, + { + "slug": "break-continue-else", + "title": "break, continue, and else", + "group": "04 · Loops" + }, + { + "slug": "loop-patterns", + "title": "Common Loop Patterns", + "group": "04 · Loops" + }, + { + "slug": "number-guessing-game", + "title": "Project: Number Guessing Game", + "group": "04 · Loops" + }, + { + "slug": "lists", + "title": "Lists", + "group": "05 · Collections" + }, + { + "slug": "list-operations-and-sorting", + "title": "Working with Lists and Sorting", + "group": "05 · Collections" + }, + { + "slug": "tuples-and-unpacking", + "title": "Tuples and Unpacking", + "group": "05 · Collections" + }, + { + "slug": "dictionaries", + "title": "Dictionaries", + "group": "05 · Collections" + }, + { + "slug": "sets", + "title": "Sets", + "group": "05 · Collections" + }, + { + "slug": "nested-data", + "title": "Nested Data", + "group": "05 · Collections" + }, + { + "slug": "comprehensions", + "title": "Comprehensions", + "group": "05 · Collections" + }, + { + "slug": "defining-functions", + "title": "Defining Functions", + "group": "06 · Functions" + }, + { + "slug": "parameters-and-arguments", + "title": "Parameters and Arguments", + "group": "06 · Functions" + }, + { + "slug": "return-values", + "title": "Return Values", + "group": "06 · Functions" + }, + { + "slug": "scope", + "title": "Variable Scope", + "group": "06 · Functions" + }, + { + "slug": "recursion", + "title": "Recursion", + "group": "06 · Functions" + }, + { + "slug": "designing-functions", + "title": "Designing Good Functions", + "group": "06 · Functions" + }, + { + "slug": "lambda-and-higher-order-functions", + "title": "Lambdas and Higher-Order Functions", + "group": "06 · Functions" + }, + { + "slug": "quiz-game", + "title": "Project: Quiz Game", + "group": "06 · Functions" + }, + { + "slug": "modules-and-imports", + "title": "Modules and Imports", + "group": "07 · Modules and the Standard Library" + }, + { + "slug": "math-random-statistics", + "title": "math, random, and statistics", + "group": "07 · Modules and the Standard Library" + }, + { + "slug": "dates-and-times", + "title": "Dates and Times", + "group": "07 · Modules and the Standard Library" + }, + { + "slug": "collections-and-itertools", + "title": "collections and itertools", + "group": "07 · Modules and the Standard Library" + }, + { + "slug": "exceptions", + "title": "Handling Exceptions", + "group": "08 · Errors and Files" + }, + { + "slug": "raising-and-custom-exceptions", + "title": "Raising and Custom Exceptions", + "group": "08 · Errors and Files" + }, + { + "slug": "input-validation", + "title": "Input Validation", + "group": "08 · Errors and Files" + }, + { + "slug": "files-and-pathlib", + "title": "Files and pathlib", + "group": "08 · Errors and Files" + }, + { + "slug": "csv", + "title": "Working with CSV", + "group": "08 · Errors and Files" + }, + { + "slug": "json", + "title": "Working with JSON", + "group": "08 · Errors and Files" + }, + { + "slug": "context-managers-basics", + "title": "The with Statement", + "group": "08 · Errors and Files" + }, + { + "slug": "expense-tracker", + "title": "Project: Expense Tracker", + "group": "08 · Errors and Files" + }, + { + "slug": "why-oop", + "title": "Why Object-Oriented Programming?", + "group": "09 · Classes and Objects" + }, + { + "slug": "classes-and-objects", + "title": "Classes and Objects", + "group": "09 · Classes and Objects" + }, + { + "slug": "methods-and-attributes", + "title": "Methods and Object State", + "group": "09 · Classes and Objects" + }, + { + "slug": "class-attributes-and-methods", + "title": "Class Attributes, Class Methods, and Static Methods", + "group": "09 · Classes and Objects" + }, + { + "slug": "properties-and-encapsulation", + "title": "Properties and Encapsulation", + "group": "09 · Classes and Objects" + }, + { + "slug": "special-methods", + "title": "Representing and Comparing Objects", + "group": "09 · Classes and Objects" + }, + { + "slug": "operators-and-containers", + "title": "Operators and Containers", + "group": "09 · Classes and Objects" + }, + { + "slug": "inheritance", + "title": "Inheritance and super()", + "group": "10 · Object-Oriented Design" + }, + { + "slug": "polymorphism-and-abcs", + "title": "Polymorphism, Duck Typing, and Abstract Classes", + "group": "10 · Object-Oriented Design" + }, + { + "slug": "composition", + "title": "Composition vs. Inheritance", + "group": "10 · Object-Oriented Design" + }, + { + "slug": "dataclasses", + "title": "Dataclasses", + "group": "10 · Object-Oriented Design" + }, + { + "slug": "enums", + "title": "Enums", + "group": "10 · Object-Oriented Design" + }, + { + "slug": "type-hints", + "title": "Type Hints", + "group": "10 · Object-Oriented Design" + }, + { + "slug": "oop-project", + "title": "Project: Library Management System", + "group": "10 · Object-Oriented Design" + }, + { + "slug": "testing-with-assert", + "title": "Testing with assert", + "group": "11 · Testing and Debugging" + }, + { + "slug": "choosing-test-cases", + "title": "Choosing Test Cases", + "group": "11 · Testing and Debugging" + }, + { + "slug": "pytest-basics", + "title": "Testing with pytest", + "group": "11 · Testing and Debugging" + }, + { + "slug": "debugging-and-logging", + "title": "Debugging and Logging", + "group": "11 · Testing and Debugging" + }, + { + "slug": "iterators-and-generators", + "title": "Iterators and Generators", + "group": "12 · Going Further" + }, + { + "slug": "regular-expressions", + "title": "Regular Expressions", + "group": "12 · Going Further" + }, + { + "slug": "text-processing-project", + "title": "Project: Text Analyzer", + "group": "12 · Going Further" + }, + { + "slug": "reading-data", + "title": "Reading Data Files", + "group": "13 · Working with Data (Optional)" + }, + { + "slug": "pandas-basics", + "title": "pandas Basics", + "group": "13 · Working with Data (Optional)" + }, + { + "slug": "charts-with-matplotlib", + "title": "Charts with matplotlib", + "group": "13 · Working with Data (Optional)" + }, + { + "slug": "data-report-project", + "title": "Project: Sales Data Report", + "group": "13 · Working with Data (Optional)" + }, + { + "slug": "closures-and-decorators", + "title": "Closures and Decorators", + "group": "14 · Advanced Python (Optional)" + }, + { + "slug": "python-data-model", + "title": "The Python Data Model", + "group": "14 · Advanced Python (Optional)" + }, + { + "slug": "context-managers-in-depth", + "title": "Context Managers in Depth", + "group": "14 · Advanced Python (Optional)" + }, + { + "slug": "async-await", + "title": "Async and await", + "group": "14 · Advanced Python (Optional)" + }, + { + "slug": "memory-and-performance", + "title": "Memory and Performance", + "group": "14 · Advanced Python (Optional)" + }, + { + "slug": "design-patterns", + "title": "Pythonic Design Patterns", + "group": "14 · Advanced Python (Optional)" + }, + { + "slug": "threads-and-processes", + "title": "Threads and Processes", + "group": "14 · Advanced Python (Optional)" + }, + { + "slug": "testing-in-depth", + "title": "Testing in Depth", + "group": "14 · Advanced Python (Optional)" + }, + { + "slug": "advanced-project", + "title": "Project: Log Pipeline", + "group": "14 · Advanced Python (Optional)" + } +] diff --git a/docs/.vitepress/quizzes/module-01.json b/docs/.vitepress/quizzes/module-01.json new file mode 100644 index 0000000..5fa3238 --- /dev/null +++ b/docs/.vitepress/quizzes/module-01.json @@ -0,0 +1,134 @@ +{ + "module": "01 · Getting Started", + "title": "Checkpoint: Getting Started", + "intro": "Check that you can run Python, print text, and read the first error messages you will meet.", + "questions": [ + { + "question": "What does this code print?", + "code": "print(\"Hello\", \"Aziza\", sep=\"-\")", + "options": [ + "Hello-Aziza", + "Hello Aziza", + "Hello-Aziza-", + "HelloAziza" + ], + "answer": 0, + "explanation": "sep sets what goes between the values, so print puts a dash instead of the usual space.", + "lesson": "hello-world" + }, + { + "question": "What happens when you run this line?", + "code": "Print(\"Salom\")", + "options": [ + "It prints Salom", + "SyntaxError", + "NameError", + "TypeError" + ], + "answer": 2, + "explanation": "Python is case-sensitive. Only print exists, so Print is an unknown name and raises NameError.", + "lesson": "what-is-python" + }, + { + "question": "You see >>> in your window, type python hello.py and get a SyntaxError. What is wrong?", + "options": [ + "The file hello.py is empty, so there is nothing to run", + "You are in the Python REPL: type exit(), then run it in the terminal", + "You must write print(python hello.py) to run a file", + "Python is not installed, so the command is not known" + ], + "answer": 1, + "explanation": "The >>> prompt means you are already inside Python, where only Python code works. Terminal commands belong at the $ or PS prompt.", + "lesson": "install-and-setup" + }, + { + "question": "A script file contains only the line below. You run it with python3 sum.py. What do you see?", + "code": "2 + 3", + "options": [ + "5", + "2 + 3", + "An error message", + "Nothing at all" + ], + "answer": 3, + "explanation": "Scripts do not show values automatically like the REPL does. Wrap the expression in print() to see it.", + "lesson": "running-python" + }, + { + "question": "What does this code print?", + "code": "print(\"Tashkent\", end=\"!\")\nprint(\"Samarkand\")", + "options": [ + "Tashkent! Samarkand", + "TashkentSamarkand!", + "Tashkent!Samarkand", + "SyntaxError" + ], + "answer": 2, + "explanation": "end=\"!\" replaces the usual newline with !, so the next print continues on the same line.", + "lesson": "hello-world" + }, + { + "question": "What does this code print?", + "code": "print(\"7 * 3 =\", 7 * 3)", + "options": [ + "7 * 3 = 21", + "21 = 21", + "7 * 3 = 7 * 3", + "7 * 3 =21" + ], + "answer": 0, + "explanation": "The part in quotes is text and is printed as-is; the part without quotes is calculated. print adds a space between them.", + "lesson": "hello-world" + }, + { + "question": "Which comment is the most useful?", + "options": [ + "count = count + 1 # add 1 to count", + "print(total) # print the total value", + "x = 5 # set x to five", + "tax_rate = 0.12 # VAT rate; check yearly" + ], + "answer": 3, + "explanation": "Good comments explain why or give context the code cannot show. The others just repeat what the code already says.", + "lesson": "comments-and-style" + }, + { + "question": "Why does this program fail?", + "code": "print(\"start\")\n print(\"next\")", + "options": [ + "print needs a colon at the end", + "The second line is indented for no reason", + "Strings cannot contain spaces", + "You cannot call print twice" + ], + "answer": 1, + "explanation": "Only code inside a block (like the body of an if) should be indented. The extra spaces cause IndentationError: unexpected indent.", + "lesson": "comments-and-style" + }, + { + "question": "Which command opens the interactive Python shell (the REPL) in a terminal on macOS or Linux?", + "options": [ + "python3", + "python3 hello.py", + "py --version", + "pip3 python" + ], + "answer": 0, + "explanation": "python3 with no file name starts the REPL, where you see the >>> prompt. python3 hello.py runs a file instead.", + "lesson": "running-python" + }, + { + "question": "In the REPL you type the line below and press Enter. Nothing appears. Why?", + "code": "total = 120 + 80", + "options": [ + "An assignment has no value to show; the REPL only echoes expressions", + "Python is still waiting for a second line of input", + "The variable name total is reserved and was ignored", + "The REPL never shows anything until you call print()" + ], + "answer": 0, + "explanation": "The REPL shows the value of an expression such as total or 2 + 3, but an assignment produces no value, so nothing is shown.", + "lesson": "running-python" + } + ] +} diff --git a/docs/.vitepress/quizzes/module-02.json b/docs/.vitepress/quizzes/module-02.json new file mode 100644 index 0000000..69b88df --- /dev/null +++ b/docs/.vitepress/quizzes/module-02.json @@ -0,0 +1,136 @@ +{ + "module": "02 · Values and Variables", + "title": "Checkpoint: Values and Variables", + "intro": "Test your understanding of variables, numbers, strings, f-strings, input, and reading errors.", + "questions": [ + { + "question": "What does this code print?", + "code": "x = 5\ny = x\nx = 10\nprint(y)", + "options": [ + "5", + "10", + "15", + "NameError" + ], + "answer": 0, + "explanation": "y = x makes y point to the value 5. Giving x a new value later does not change y.", + "lesson": "variables" + }, + { + "question": "What does this code print?", + "code": "print(7 // 2, 7 % 2)", + "options": [ + "3.5 1", + "4 1", + "3 1", + "3 0.5" + ], + "answer": 2, + "explanation": "// gives the whole part of the division (3) and % gives the remainder (1).", + "lesson": "numbers-and-math" + }, + { + "question": "What does this code print?", + "code": "print(10 / 2, 10 // 2)", + "options": [ + "5 5", + "5.0 5", + "5.0 5.0", + "5 5.0" + ], + "answer": 1, + "explanation": "/ always gives a float, even when the division is exact. // gives an int when both sides are ints.", + "lesson": "numbers-and-math" + }, + { + "question": "What does this code print?", + "code": "word = \"Tashkent\"\nprint(word[-1], word[0:4])", + "options": [ + "n Tashk", + "t Tashk", + "T Tash", + "t Tash" + ], + "answer": 3, + "explanation": "Index -1 is the last character, and a slice stops before the stop index, so [0:4] gives the first 4 characters.", + "lesson": "string-methods-and-slicing" + }, + { + "question": "What does this code print?", + "code": "city = \"tashkent\"\ncity.capitalize()\nprint(city)", + "options": [ + "Tashkent", + "TASHKENT", + "tashkent", + "None" + ], + "answer": 2, + "explanation": "String methods return a new string; they never change the original. Save the result: city = city.capitalize().", + "lesson": "string-methods-and-slicing" + }, + { + "question": "What does this code print?", + "code": "price = 12500.5\nprint(f\"{price:,.2f} som\")", + "options": [ + "12,500.50 som", + "12,500.5 som", + "12500.50 som", + "12,501 som" + ], + "answer": 0, + "explanation": ", adds a thousands separator and .2f shows exactly two decimal places.", + "lesson": "f-strings" + }, + { + "question": "The user types 20. What does this code print?", + "code": "age = input(\"Age: \")\nprint(age * 2)", + "options": [ + "40", + "TypeError", + "20 20", + "2020" + ], + "answer": 3, + "explanation": "input() always returns a string, and a string times 2 repeats it. Convert first with int(input(...)).", + "lesson": "type-conversion-and-input" + }, + { + "question": "What happens when you run this code?", + "code": "total = 100\nprint(\"Total: \" + total)", + "options": [ + "It prints Total: 100", + "TypeError", + "ValueError", + "NameError" + ], + "answer": 1, + "explanation": "Python will not join a string and an int automatically. Use str(total) or an f-string.", + "lesson": "strings-basics" + }, + { + "question": "What happens when you run this code?", + "code": "price = int(\"12.5\")\nprint(price)", + "options": [ + "12", + "12.5", + "ValueError", + "TypeError" + ], + "answer": 2, + "explanation": "int() cannot read text that contains a decimal point. Use float() when the value can have decimals.", + "lesson": "type-conversion-and-input" + }, + { + "question": "A long traceback appears on your screen. Where should you look first?", + "options": [ + "The first line, Traceback (most recent call last):", + "The last line, which names the error and describes it", + "The middle lines only", + "Nowhere; just change code until it works" + ], + "answer": 1, + "explanation": "The useful information is at the bottom: the error type and message. The lines above show where it happened.", + "lesson": "reading-errors-and-debugging" + } + ] +} diff --git a/docs/.vitepress/quizzes/module-03.json b/docs/.vitepress/quizzes/module-03.json new file mode 100644 index 0000000..88b2404 --- /dev/null +++ b/docs/.vitepress/quizzes/module-03.json @@ -0,0 +1,136 @@ +{ + "module": "03 · Making Decisions", + "title": "Checkpoint: Making Decisions", + "intro": "Check how well you can compare values, combine conditions, and choose between branches with if and match.", + "questions": [ + { + "question": "What does this code print?", + "code": "answer = \"7\"\nprint(answer == 7)", + "options": [ + "False", + "True", + "7", + "TypeError" + ], + "answer": 0, + "explanation": "\"7\" is a string and 7 is a number, so they are never equal. Convert with int(answer) before comparing.", + "lesson": "booleans-and-comparisons" + }, + { + "question": "What does this code print?", + "code": "print(bool(\"\"), bool(\"0\"))", + "options": [ + "False False", + "True True", + "False True", + "True False" + ], + "answer": 2, + "explanation": "An empty string is falsy, but any non-empty string is truthy, even \"0\".", + "lesson": "booleans-and-comparisons" + }, + { + "question": "What does this code print?", + "code": "print(1 < 5 < 3)", + "options": [ + "True", + "False", + "SyntaxError", + "3" + ], + "answer": 1, + "explanation": "A chained comparison means 1 < 5 and 5 < 3. The second part is False, so the whole thing is False.", + "lesson": "booleans-and-comparisons" + }, + { + "question": "What does this code print?", + "code": "temp = 30\nif temp > 10:\n print(\"Warm\")\nelif temp > 20:\n print(\"Hot\")\nelse:\n print(\"Cold\")", + "options": [ + "Hot", + "Hot and Warm", + "Cold", + "Warm" + ], + "answer": 3, + "explanation": "Python checks conditions from top to bottom and runs only the first true branch. 30 > 10 is true, so it never reaches the Hot check.", + "lesson": "if-elif-else" + }, + { + "question": "What does this code print?", + "code": "answer = \"no\"\nif answer == \"yes\" or \"y\":\n print(\"OK\")\nelse:\n print(\"Cancelled\")", + "options": [ + "SyntaxError", + "Cancelled", + "OK", + "Nothing" + ], + "answer": 2, + "explanation": "This reads as (answer == \"yes\") or \"y\", and the non-empty string \"y\" is always truthy. Write answer in (\"yes\", \"y\") instead.", + "lesson": "logical-operators" + }, + { + "question": "What does this code print?", + "code": "print(True or False and False)", + "options": [ + "True", + "False", + "None", + "SyntaxError" + ], + "answer": 0, + "explanation": "and is evaluated before or, so this is True or (False and False), which is True.", + "lesson": "logical-operators" + }, + { + "question": "Which condition safely avoids dividing by zero?", + "options": [ + "total / count > 10 and count != 0", + "not count and total / count > 10", + "count != 0 or total / count > 10", + "count != 0 and total / count > 10" + ], + "answer": 3, + "explanation": "and stops as soon as the left side is False, so the guard must come first to skip the division.", + "lesson": "logical-operators" + }, + { + "question": "What does this code print?", + "code": "command = \"halt\"\nmatch command:\n case \"go\" | \"start\":\n print(\"Moving\")\n case \"stop\" | \"halt\":\n print(\"Stopping\")\n case _:\n print(\"Unknown command\")", + "options": [ + "Moving", + "Stopping", + "Unknown command", + "Nothing" + ], + "answer": 1, + "explanation": "| lets one case match several values. \"halt\" matches the second case.", + "lesson": "match-statement" + }, + { + "question": "What does this code print?", + "code": "color = \"green\"\nmatch color:\n case \"red\":\n print(\"Stop\")\n case other:\n print(\"Unknown:\", other)", + "options": [ + "Unknown: green", + "Nothing at all", + "NameError", + "SyntaxError" + ], + "answer": 0, + "explanation": "A bare name in a case pattern is a capture pattern: it matches any value and binds it, so the last case always runs when nothing before it matched. That is why it must come last.", + "lesson": "match-statement" + }, + { + "question": "What is wrong with this code?", + "code": "age = 18\nif age = 18:\n print(\"Just turned 18\")", + "options": [ + "Nothing, it prints Just turned 18", + "It uses = instead of ==, so Python raises SyntaxError", + "The if needs parentheses around the condition", + "print must not be indented" + ], + "answer": 1, + "explanation": "A single = assigns a value; comparing needs ==. Python stops with a SyntaxError and even suggests the fix.", + "lesson": "if-elif-else" + } + ] +} diff --git a/docs/.vitepress/quizzes/module-04.json b/docs/.vitepress/quizzes/module-04.json new file mode 100644 index 0000000..dc8743c --- /dev/null +++ b/docs/.vitepress/quizzes/module-04.json @@ -0,0 +1,135 @@ +{ + "module": "04 · Loops", + "title": "Checkpoint: Loops", + "intro": "Check that you can trace while and for loops, control them with break and continue, and use common loop patterns.", + "questions": [ + { + "question": "What does this code print?", + "code": "for i in range(1, 10, 3):\n print(i, end=\" \")", + "options": [ + "1 3 5 7 9", + "1 4 7", + "0 3 6 9", + "1 4 7 10" + ], + "answer": 1, + "explanation": "range(1, 10, 3) starts at 1, steps by 3, and stops before 10.", + "lesson": "for-loops-and-range" + }, + { + "question": "What does this code print?", + "code": "count = 1\nwhile count <= 3:\n count += 1\n print(count, end=\" \")", + "options": [ + "2 3 4", + "1 2 3", + "1 2 3 4", + "2 3" + ], + "answer": 0, + "explanation": "The update happens before print, so each printed value is already one bigger. Usually the update should come last.", + "lesson": "while-loops" + }, + { + "question": "What does this code print?", + "code": "for n in range(1, 4):\n total = 0\n total += n\nprint(total)", + "options": [ + "3", + "0", + "10", + "6" + ], + "answer": 0, + "explanation": "total is reset to 0 on every iteration, so only the last number survives. Create total = 0 before the loop.", + "lesson": "for-loops-and-range" + }, + { + "question": "What happens when you run this code?", + "code": "for i in 5:\n print(i)", + "options": [ + "SyntaxError", + "It prints 1 to 5", + "TypeError", + "It prints 0 to 4" + ], + "answer": 2, + "explanation": "A number is not a sequence you can loop over. Use range(5) to loop five times.", + "lesson": "for-loops-and-range" + }, + { + "question": "What does this code print?", + "code": "for n in range(1, 6):\n if n == 3:\n continue\n if n == 5:\n break\n print(n, end=\" \")", + "options": [ + "1 2", + "1 2 3 4", + "1 2 4 5", + "1 2 4" + ], + "answer": 3, + "explanation": "continue skips 3 and moves on; break stops the loop when n is 5, before it is printed.", + "lesson": "break-continue-else" + }, + { + "question": "What does this code print?", + "code": "for name in [\"Aziza\", \"Bekzod\"]:\n if name == \"Dilnoza\":\n print(\"Found\")\n break\nelse:\n print(\"Not found\")", + "options": [ + "Found", + "Nothing", + "Not found", + "Found and Not found" + ], + "answer": 2, + "explanation": "A loop's else runs when the loop finishes without break. Dilnoza is never found, so break never happens.", + "lesson": "break-continue-else" + }, + { + "question": "You have a for loop inside another for loop. What does break in the inner loop do?", + "options": [ + "Stops both the inner and the outer loop", + "Skips one iteration of the inner loop", + "Stops the whole program at once", + "Stops only the inner loop" + ], + "answer": 3, + "explanation": "break leaves only the innermost loop. Use a flag or a function with return to stop both.", + "lesson": "break-continue-else" + }, + { + "question": "What does this code print?", + "code": "temps = [-5, -2, -9]\nhighest = 0\nfor t in temps:\n if t > highest:\n highest = t\nprint(highest)", + "options": [ + "-2", + "0", + "-9", + "-5" + ], + "answer": 1, + "explanation": "Starting highest at 0 is a bug: no negative number beats it, so 0 is printed even though it is not in the list. Start with the first item.", + "lesson": "loop-patterns" + }, + { + "question": "What does this code print?", + "code": "n = 3\nwhile n > 0:\n n -= 1\nelse:\n print(\"done\", n)", + "options": [ + "done 0", + "done 3", + "Nothing at all", + "SyntaxError" + ], + "answer": 0, + "explanation": "A while loop's else block runs when the condition becomes false (no break happened). By then n has reached 0.", + "lesson": "break-continue-else" + }, + { + "question": "You need to print each name with its position (1, 2, 3...). Which is the clearest way?", + "options": [ + "for i in range(len(names)):\n print(i + 1, names[i])", + "for i, name in enumerate(names, start=1):\n print(i, name)", + "for name in names:\n print(names.index(name) + 1, name)", + "i = 0\nwhile True:\n print(i, names[i])" + ], + "answer": 1, + "explanation": "enumerate() gives you both the position and the item, and start=1 counts from 1.", + "lesson": "loop-patterns" + } + ] +} diff --git a/docs/.vitepress/quizzes/module-05.json b/docs/.vitepress/quizzes/module-05.json new file mode 100644 index 0000000..b38e08a --- /dev/null +++ b/docs/.vitepress/quizzes/module-05.json @@ -0,0 +1,137 @@ +{ + "module": "05 · Collections", + "title": "Checkpoint: Collections", + "intro": "Test your knowledge of lists, tuples, dictionaries, sets, nested data, and comprehensions.", + "questions": [ + { + "question": "What does this code print?", + "code": "words = [\"kiwi\", \"fig\", \"apple\"]\nprint(sorted(words, key=len))", + "options": [ + "['fig', 'kiwi', 'apple']", + "['apple', 'fig', 'kiwi']", + "['kiwi', 'fig', 'apple']", + "[3, 4, 5]" + ], + "answer": 0, + "explanation": "key=len sorts by the length of each word (3, 4, 5). The key only decides the order; the original words are returned.", + "lesson": "list-operations-and-sorting" + }, + { + "question": "What does this code print?", + "code": "a = [1, 2, 3]\nb = a\nb.append(4)\nprint(a)", + "options": [ + "[1, 2, 3]", + "[4]", + "[1, 2, 3, 4]", + "None" + ], + "answer": 2, + "explanation": "b = a does not make a copy; both names point to the same list. Use a.copy() to get a separate list.", + "lesson": "lists" + }, + { + "question": "What does this code print?", + "code": "scores = [3, 1, 2]\nranked = sorted(scores)\nprint(scores, ranked)", + "options": [ + "[1, 2, 3] [1, 2, 3]", + "[3, 1, 2] [1, 2, 3]", + "[3, 1, 2] None", + "None [1, 2, 3]" + ], + "answer": 1, + "explanation": "sorted() returns a new sorted list and leaves the original unchanged, unlike .sort().", + "lesson": "list-operations-and-sorting" + }, + { + "question": "What does this code print?", + "code": "colors = (\"red\")\nprint(len(colors))", + "options": [ + "1", + "0", + "TypeError", + "3" + ], + "answer": 3, + "explanation": "Without a comma, (\"red\") is just the string \"red\" in parentheses, which has 3 characters. A one-item tuple needs a comma: (\"red\",).", + "lesson": "tuples-and-unpacking" + }, + { + "question": "What happens when you run this code?", + "code": "name, age = (\"Aziza\", 20, \"Tashkent\")\nprint(name, age)", + "options": [ + "It prints Aziza 20", + "TypeError", + "ValueError", + "IndexError" + ], + "answer": 2, + "explanation": "There are 3 values but only 2 variables. Match the count, or collect the extra with *rest.", + "lesson": "tuples-and-unpacking" + }, + { + "question": "What does this code print?", + "code": "capitals = {\"Uzbekistan\": \"Tashkent\", \"Japan\": \"Tokyo\"}\nprint(\"Tokyo\" in capitals)", + "options": [ + "False", + "True", + "Tokyo", + "KeyError" + ], + "answer": 0, + "explanation": "in checks the keys of a dictionary, not the values. Use \"Tokyo\" in capitals.values() to search values.", + "lesson": "dictionaries" + }, + { + "question": "What does this code print?", + "code": "user = {\"name\": \"Aziza\"}\nprint(user.get(\"email\", \"unknown\"))", + "options": [ + "email", + "None", + "KeyError", + "unknown" + ], + "answer": 3, + "explanation": ".get() returns the default you give it when the key is missing, instead of raising KeyError.", + "lesson": "dictionaries" + }, + { + "question": "What happens when you run this code?", + "code": "items = {}\nitems.add(\"x\")\nprint(items)", + "options": [ + "It prints {'x'}", + "AttributeError", + "KeyError", + "It prints {}" + ], + "answer": 1, + "explanation": "{} creates an empty dictionary, not a set, and dictionaries have no add method. Use set() for an empty set.", + "lesson": "sets" + }, + { + "question": "What does this code print?", + "code": "grid = [[0] * 3] * 3\ngrid[0][0] = 1\nprint(grid[1])", + "options": [ + "[0, 0, 0]", + "[1, 1, 1]", + "[1, 0, 0]", + "IndexError" + ], + "answer": 2, + "explanation": "[[0] * 3] * 3 repeats the same inner list three times, so changing one row changes them all. Build rows with a comprehension instead.", + "lesson": "nested-data" + }, + { + "question": "What does this code print?", + "code": "print([n * 2 for n in range(5) if n % 2 == 0])", + "options": [ + "[0, 2, 4, 6, 8]", + "[0, 4, 8]", + "[2, 6]", + "[0, 1, 2, 3, 4]" + ], + "answer": 1, + "explanation": "The if keeps only the even numbers 0, 2, 4, and each one is doubled.", + "lesson": "comprehensions" + } + ] +} diff --git a/docs/.vitepress/quizzes/module-06.json b/docs/.vitepress/quizzes/module-06.json new file mode 100644 index 0000000..71822a2 --- /dev/null +++ b/docs/.vitepress/quizzes/module-06.json @@ -0,0 +1,136 @@ +{ + "module": "06 · Functions", + "title": "Checkpoint: Functions", + "intro": "Check that you can define functions, pass arguments, return values, and reason about scope.", + "questions": [ + { + "question": "What is stored in result after this code runs?", + "code": "def double(n):\n print(n * 2)\n\nresult = double(5)", + "options": [ + "None", + "10", + "20", + "0" + ], + "answer": 0, + "explanation": "The function prints 10 but has no return statement, so it gives back None.", + "lesson": "return-values" + }, + { + "question": "What happens when you run this code?", + "code": "def greet(name, greeting):\n print(f\"{greeting}, {name}!\")\n\ngreet(\"Aziza\")", + "options": [ + "It prints Hello, Aziza!", + "It prints None, Aziza!", + "TypeError", + "NameError" + ], + "answer": 2, + "explanation": "greet has two required parameters but only one argument was passed. Pass both, or give greeting a default value.", + "lesson": "defining-functions" + }, + { + "question": "What does this code print?", + "code": "def power(base, exp=2):\n return base ** exp\n\nprint(power(3), power(2, exp=3))", + "options": [ + "6 8", + "9 8", + "9 9", + "3 6" + ], + "answer": 1, + "explanation": "power(3) uses the default exp=2, so 3 ** 2 is 9. The keyword argument exp=3 overrides it: 2 ** 3 is 8.", + "lesson": "parameters-and-arguments" + }, + { + "question": "What does this code print?", + "code": "def add_item(item, items=[]):\n items.append(item)\n return items\n\nadd_item(\"a\")\nprint(add_item(\"b\"))", + "options": [ + "['b']", + "[]", + "['a']", + "['a', 'b']" + ], + "answer": 3, + "explanation": "A default list is created once, when the function is defined, and shared between calls. Use items=None and create the list inside.", + "lesson": "parameters-and-arguments" + }, + { + "question": "What does this code print?", + "code": "def total(*prices):\n return sum(prices)\n\nprint(total(1000, 2000), total())", + "options": [ + "3000 0", + "3000 TypeError", + "TypeError", + "(1000, 2000) ()" + ], + "answer": 0, + "explanation": "*prices collects any number of positional arguments into a tuple, so total() with no arguments gets an empty tuple and sum(()) is 0.", + "lesson": "parameters-and-arguments" + }, + { + "question": "What happens when you run this code?", + "code": "count = 0\n\ndef increment():\n count += 1\n\nincrement()\nprint(count)", + "options": [ + "UnboundLocalError", + "It prints 0", + "It prints 1", + "SyntaxError" + ], + "answer": 0, + "explanation": "Assigning to count inside the function makes it local, so count += 1 reads it before it has a value. Pass it in and return the result instead.", + "lesson": "scope" + }, + { + "question": "What does this code print?", + "code": "def clear(items):\n items = []\n\ndata = [1, 2, 3]\nclear(data)\nprint(data)", + "options": [ + "[]", + "UnboundLocalError", + "None", + "[1, 2, 3]" + ], + "answer": 3, + "explanation": "items = [] only points the local name at a new list; the caller's list is untouched. items.clear() would change it.", + "lesson": "scope" + }, + { + "question": "Which version of this function is easiest to reuse and test?", + "options": [ + "def total():\n price = float(input(\"Price: \"))\n print(price * 1.12)", + "def total(price, tax_rate):\n return price * (1 + tax_rate)", + "def total(price):\n print(price * 1.12)", + "def total():\n global price\n price = price * 1.12" + ], + "answer": 1, + "explanation": "It takes its inputs as parameters and returns the result, with no input(), print(), or globals tying it to one situation.", + "lesson": "designing-functions" + }, + { + "question": "What does this code print?", + "code": "items = [(\"non\", 5000), (\"choy\", 3000), (\"osh\", 25000)]\ncheapest = sorted(items, key=lambda x: x[1])[0]\nprint(cheapest[0])", + "options": [ + "non", + "osh", + "choy", + "3000" + ], + "answer": 2, + "explanation": "The lambda tells sorted to compare the prices, so the cheapest item, choy, comes first.", + "lesson": "lambda-and-higher-order-functions" + }, + { + "question": "What does this code print?", + "code": "result = map(str.upper, [\"a\", \"b\"])\nprint(list(result), list(result))", + "options": [ + "['A', 'B'] ['A', 'B']", + "['A', 'B'] []", + " []", + "TypeError" + ], + "answer": 1, + "explanation": "A map object can only be looped over once. The first list() uses it up, so the second one gets nothing.", + "lesson": "lambda-and-higher-order-functions" + } + ] +} diff --git a/docs/.vitepress/quizzes/module-07.json b/docs/.vitepress/quizzes/module-07.json new file mode 100644 index 0000000..74ba835 --- /dev/null +++ b/docs/.vitepress/quizzes/module-07.json @@ -0,0 +1,135 @@ +{ + "module": "07 · Modules and the Standard Library", + "title": "Checkpoint: Modules and the Standard Library", + "intro": "Check that you can import modules and use math, random, statistics, datetime, and collections.", + "questions": [ + { + "question": "What happens when you run this code?", + "code": "from math import sqrt\n\nprint(math.sqrt(25))", + "options": [ + "NameError", + "It prints 5.0", + "ImportError", + "AttributeError" + ], + "answer": 0, + "explanation": "from math import sqrt defines only the name sqrt, not math. Write sqrt(25), or use import math.", + "lesson": "modules-and-imports" + }, + { + "question": "Bekzod saves his dice game as random.py, and random.randint suddenly stops working. Why?", + "options": [ + "random is not part of the standard library", + "Files cannot contain the word import", + "Python finds his own random.py first, instead of the real module", + "He must write import random.py" + ], + "answer": 2, + "explanation": "Python looks in the script's own folder first. Rename the file to something like dice_game.py.", + "lesson": "modules-and-imports" + }, + { + "question": "What does if __name__ == \"__main__\": let you do?", + "options": [ + "Make the functions in the file run faster", + "Run code only when the file is run directly", + "Import every name from another module", + "Mark the first function Python should read" + ], + "answer": 1, + "explanation": "When another file imports your module, __name__ is the module name, so the code under this check is skipped.", + "lesson": "modules-and-imports" + }, + { + "question": "What does this code print?", + "code": "import math\n\nprint(math.floor(-3.7), math.ceil(-3.7))", + "options": [ + "-3 -4", + "-4 -4", + "-3 -3", + "-4 -3" + ], + "answer": 3, + "explanation": "floor always goes down and ceil always goes up, even for negative numbers.", + "lesson": "math-random-statistics" + }, + { + "question": "What does this code print?", + "code": "import random\n\nnames = [\"Aziza\", \"Bekzod\", \"Dilnoza\"]\nshuffled = random.shuffle(names)\nprint(shuffled)", + "options": [ + "['Aziza', 'Bekzod', 'Dilnoza']", + "A shuffled list", + "None", + "TypeError" + ], + "answer": 2, + "explanation": "shuffle changes the list in place and returns None. Use names after shuffling, or random.sample() for a new list.", + "lesson": "math-random-statistics" + }, + { + "question": "What does this code print?", + "code": "import statistics\n\nprint(statistics.median([3, 1, 4, 10]))", + "options": [ + "3.5", + "4.5", + "4", + "3" + ], + "answer": 0, + "explanation": "median sorts the data first (1, 3, 4, 10) and averages the two middle values. 4.5 would be the mean.", + "lesson": "math-random-statistics" + }, + { + "question": "What does this code print?", + "code": "from datetime import date, timedelta\n\nd = date(2026, 9, 15) + timedelta(days=20)\nprint(d)", + "options": [ + "2026-09-35", + "TypeError", + "2026-10-15", + "2026-10-05" + ], + "answer": 3, + "explanation": "timedelta handles month lengths for you: 20 days after 15 September is 5 October.", + "lesson": "dates-and-times" + }, + { + "question": "What does this code print?", + "code": "from collections import Counter\n\nletters = Counter(\"banana\")\nprint(letters.most_common(1))", + "options": [ + "[('b', 1)]", + "[('a', 3)]", + "[('n', 2)]", + "{'a': 3}" + ], + "answer": 1, + "explanation": "Counter counts each letter, and most_common(1) returns a list with the single most frequent (item, count) pair.", + "lesson": "collections-and-itertools" + }, + { + "question": "What does this code print?", + "code": "from collections import defaultdict\n\ntotals = defaultdict(int)\nprint(totals[\"Nukus\"], len(totals))", + "options": [ + "0 1", + "KeyError", + "0 0", + "None 1" + ], + "answer": 0, + "explanation": "Reading a missing key from a defaultdict inserts it with the default value, so the lookup returns 0 and the dictionary now has one entry. Use 'Nukus' in totals or totals.get('Nukus', 0) to look without inserting.", + "lesson": "collections-and-itertools" + }, + { + "question": "What does this code print?", + "code": "from datetime import datetime\n\nd = datetime(2026, 9, 15, 14, 30)\nprint(d.strftime(\"%d.%M.%Y\"))", + "options": [ + "15.09.2026", + "15.30.2026", + "15.9.2026", + "ValueError" + ], + "answer": 1, + "explanation": "%M is minutes; the month is %m (lowercase). A wrong code does not raise an error, it just formats the wrong field.", + "lesson": "dates-and-times" + } + ] +} diff --git a/docs/.vitepress/quizzes/module-08.json b/docs/.vitepress/quizzes/module-08.json new file mode 100644 index 0000000..b604d6e --- /dev/null +++ b/docs/.vitepress/quizzes/module-08.json @@ -0,0 +1,136 @@ +{ + "module": "08 · Errors and Files", + "title": "Checkpoint: Errors and Files", + "intro": "Check that you can handle exceptions, validate input, and read and write text, CSV, and JSON files safely.", + "questions": [ + { + "question": "Which lines does this code print, in order?", + "code": "def check(text):\n try:\n n = int(text)\n except ValueError:\n print(\"rejected\")\n else:\n print(\"accepted\")\n finally:\n print(\"done\")\n\ncheck(\"12\")", + "options": [ + "accepted, then done", + "accepted", + "rejected, then done", + "done, then accepted" + ], + "answer": 0, + "explanation": "The try block succeeds, so else runs; finally always runs afterwards.", + "lesson": "exceptions" + }, + { + "question": "What does this code print?", + "code": "try:\n result = 10 / 0\nexcept Exception:\n print(\"Something went wrong\")\nexcept ZeroDivisionError:\n print(\"Cannot divide by zero\")", + "options": [ + "Cannot divide by zero", + "Something went wrong", + "Both messages", + "Nothing, the program crashes" + ], + "answer": 1, + "explanation": "ZeroDivisionError is a child of Exception, so the first matching except wins. Put specific exceptions first.", + "lesson": "exceptions" + }, + { + "question": "What does this code print?", + "code": "class OutOfStockError(Exception):\n pass\n\ndef buy(stock):\n if stock == 0:\n raise OutOfStockError(\"no tea left\")\n return stock - 1\n\ntry:\n buy(0)\nexcept OutOfStockError as e:\n print(f\"Error: {e}\")", + "options": [ + "Error: OutOfStockError", + "Nothing, the program crashes", + "Error: no tea left", + "TypeError" + ], + "answer": 2, + "explanation": "The custom class inherits from Exception, so it can carry a message, and str(e) gives that message.", + "lesson": "raising-and-custom-exceptions" + }, + { + "question": "Which call turns the text below (a string) into a Python dictionary?", + "code": "text = '{\"city\": \"Nukus\", \"temp\": 28}'", + "options": [ + "json.loads(text)", + "json.load(text)", + "json.dumps(text)", + "json.dump(text)" + ], + "answer": 0, + "explanation": "loads reads from a string (the s is for string); load reads from an open file. dumps and dump go the other way, from Python to JSON.", + "lesson": "json" + }, + { + "question": "The user typed \" Yes\" (with a leading space). What does this code print?", + "code": "answer = \" Yes\"\nif answer == \"yes\":\n print(\"Confirmed\")\nelse:\n print(\"Not confirmed\")", + "options": [ + "Confirmed", + "Not confirmed", + "ValueError", + "Nothing at all" + ], + "answer": 1, + "explanation": "\" Yes\" is not equal to \"yes\": the space and the capital letter both matter. Normalize first with answer.strip().lower() and then compare.", + "lesson": "input-validation" + }, + { + "question": "Why is \"-3\".isdigit() a poor way to check that a temperature is a valid number?", + "options": [ + "It raises ValueError for negative numbers", + "It returns True for every non-empty string", + "It returns False, so valid negatives are rejected", + "It only works for float strings such as 3.5" + ], + "answer": 2, + "explanation": "The minus sign is not a digit, so isdigit() returns False. Convert with int() or float() inside try instead.", + "lesson": "input-validation" + }, + { + "question": "What does this code print?", + "code": "with open(\"log.txt\", \"w\", encoding=\"utf-8\") as f:\n f.write(\"first\\n\")\nwith open(\"log.txt\", \"w\", encoding=\"utf-8\") as f:\n f.write(\"second\\n\")\nwith open(\"log.txt\", encoding=\"utf-8\") as f:\n print(f.read(), end=\"\")", + "options": [ + "first and second (two lines)", + "first", + "Nothing", + "second" + ], + "answer": 3, + "explanation": "Mode \"w\" erases the file each time it is opened. Use \"a\" to append.", + "lesson": "files-and-pathlib" + }, + { + "question": "What happens when this code runs?", + "code": "import csv, io\nrows = csv.DictReader(io.StringIO(\"name,score\\nAziza,92\\nBekzod,78\\n\"))\ntotal = sum(row[\"score\"] for row in rows)\nprint(total)", + "options": [ + "It prints 170", + "TypeError", + "ValueError", + "It prints 9278" + ], + "answer": 1, + "explanation": "Every CSV value is a string, so sum() tries to add an int and a str. Convert with int(row[\"score\"]).", + "lesson": "csv" + }, + { + "question": "What does this code print?", + "code": "import json\nmedals = {1: \"gold\", 2: \"silver\"}\ndata = json.loads(json.dumps(medals))\nprint(data)", + "options": [ + "{'1': 'gold', '2': 'silver'}", + "{1: 'gold', 2: 'silver'}", + "[1, 2]", + "TypeError" + ], + "answer": 0, + "explanation": "JSON object keys are always strings, so number keys come back as strings after a round trip.", + "lesson": "json" + }, + { + "question": "What happens on the last line?", + "code": "with open(\"notes.txt\", \"w\", encoding=\"utf-8\") as file:\n file.write(\"first line\\n\")\nfile.write(\"second line\\n\")", + "options": [ + "The text is appended to notes.txt", + "The file is reopened automatically", + "ValueError", + "NameError" + ], + "answer": 2, + "explanation": "The with block closes the file when it ends, and writing to a closed file raises ValueError: I/O operation on closed file.", + "lesson": "context-managers-basics" + } + ] +} diff --git a/docs/.vitepress/quizzes/module-09.json b/docs/.vitepress/quizzes/module-09.json new file mode 100644 index 0000000..c3daeae --- /dev/null +++ b/docs/.vitepress/quizzes/module-09.json @@ -0,0 +1,136 @@ +{ + "module": "09 · Classes and Objects", + "title": "Checkpoint: Classes and Objects", + "intro": "Check that you can define classes, work with instance and class attributes, use properties, and write special methods.", + "questions": [ + { + "question": "What does this code print?", + "code": "class Temperature:\n def __init__(self, celsius):\n self.celsius = celsius\n\n @classmethod\n def from_fahrenheit(cls, f):\n return cls((f - 32) * 5 / 9)\n\nt = Temperature.from_fahrenheit(212)\nprint(t.celsius)", + "options": [ + "100.0", + "212", + "TypeError", + "100" + ], + "answer": 0, + "explanation": "A classmethod receives the class as cls, so cls(...) builds a new Temperature. (212 - 32) * 5 / 9 is 100.0, a float because of /.", + "lesson": "class-attributes-and-methods" + }, + { + "question": "What happens when this code runs?", + "code": "class Book:\n def __init__(self, title):\n title = title\n\nbook = Book(\"Python Basics\")\nprint(book.title)", + "options": [ + "It prints Python Basics", + "It prints None", + "TypeError", + "AttributeError" + ], + "answer": 3, + "explanation": "Without self., title is only a local variable inside __init__, so the object never gets a title attribute.", + "lesson": "classes-and-objects" + }, + { + "question": "What happens on the last line?", + "code": "class Todo:\n def __init__(self):\n self.tasks = []\n\n def add(self, task):\n self.tasks.append(task)\n\ntodo = Todo().add(\"buy bread\")\nprint(todo.tasks)", + "options": [ + "It prints ['buy bread']", + "AttributeError", + "TypeError", + "It prints None" + ], + "answer": 1, + "explanation": "add() returns None, so todo is None. Create the object first, then call add() on its own line.", + "lesson": "methods-and-attributes" + }, + { + "question": "What does this code print?", + "code": "class Wallet:\n def __init__(self):\n self.cash = 1000\n def spend(self, amount):\n self.cash -= amount\n if self.cash < 0:\n raise ValueError(\"Not enough cash\")\nw = Wallet()\ntry:\n w.spend(5000)\nexcept ValueError:\n print(w.cash)", + "options": [ + "1000", + "-4000", + "ValueError", + "0" + ], + "answer": 1, + "explanation": "The state changes before it is validated: self.cash is reduced first, and the exception is raised afterwards (and then caught), so the wallet ends up at -4000. Validate first, then change state.", + "lesson": "methods-and-attributes" + }, + { + "question": "What does this code print?", + "code": "class Student:\n count = 0\n\n def __init__(self, name):\n self.name = name\n self.count += 1\n\na = Student(\"Aziza\")\nb = Student(\"Bekzod\")\nprint(Student.count, a.count)", + "options": [ + "2 1", + "2 2", + "0 1", + "AttributeError" + ], + "answer": 2, + "explanation": "self.count += 1 creates an instance attribute on each object and leaves Student.count at 0. Use Student.count += 1.", + "lesson": "class-attributes-and-methods" + }, + { + "question": "What happens when this code runs?", + "code": "class Rectangle:\n def __init__(self, width, height):\n self.width = width\n self.height = height\n\n @property\n def area(self):\n return self.width * self.height\n\nprint(Rectangle(4, 5).area())", + "options": [ + "It prints 20", + "It prints the method object", + "AttributeError", + "TypeError" + ], + "answer": 3, + "explanation": "A property is read without parentheses: Rectangle(4, 5).area is already the number 20, and a number cannot be called.", + "lesson": "properties-and-encapsulation" + }, + { + "question": "A Product class has a property named price. Inside the class, where should the value itself be stored?", + "options": [ + "self.price", + "self._price", + "Product.price", + "A global variable" + ], + "answer": 1, + "explanation": "Assigning to self.price inside the property calls the setter again and again, causing RecursionError. Store the data under another name like self._price.", + "lesson": "properties-and-encapsulation" + }, + { + "question": "What does this code print?", + "code": "class Product:\n def __init__(self, name):\n self.name = name\n\n def __repr__(self):\n return f\"Product({self.name!r})\"\n\n def __str__(self):\n return self.name\n\nitems = [Product(\"Tea\")]\nprint(items[0], items)", + "options": [ + "Tea [Product('Tea')]", + "Tea [Tea]", + "Product('Tea') [Product('Tea')]", + "Tea ['Tea']" + ], + "answer": 0, + "explanation": "print() uses __str__ for the object itself, but a list shows its items with __repr__.", + "lesson": "special-methods" + }, + { + "question": "What does this code do?", + "code": "class Product:\n def __init__(self, name, price):\n self.name = name\n self.price = price\n\n def __eq__(self, other):\n return self.name == other.name\n\nprint(Product(\"Tea\", 15000) == Product(\"Tea\", 12000))\nprint({Product(\"Tea\", 15000)})", + "options": [ + "Prints True, then a set with one product", + "Prints False, then raises TypeError", + "Prints True, then raises TypeError", + "Prints True, then a set with two products" + ], + "answer": 2, + "explanation": "The names match, so == is True. Defining __eq__ sets __hash__ to None, so the object cannot go in a set.", + "lesson": "special-methods" + }, + { + "question": "What does this code print?", + "code": "class Cart:\n def __init__(self, items):\n self.items = items\n\n def __len__(self):\n return len(self.items)\n\ncart = Cart([\"tea\", \"non\"])\nprint(len(cart), bool(Cart([])))", + "options": [ + "2 False", + "2 True", + "TypeError", + "AttributeError" + ], + "answer": 0, + "explanation": "len(cart) calls __len__. With no __bool__, truth testing falls back to __len__, so an empty cart is False.", + "lesson": "operators-and-containers" + } + ] +} diff --git a/docs/.vitepress/quizzes/module-10.json b/docs/.vitepress/quizzes/module-10.json new file mode 100644 index 0000000..ac975b3 --- /dev/null +++ b/docs/.vitepress/quizzes/module-10.json @@ -0,0 +1,135 @@ +{ + "module": "10 · Object-Oriented Design", + "title": "Checkpoint: Object-Oriented Design", + "intro": "Check that you can choose between inheritance and composition, use ABCs, dataclasses, and enums, and read type hints correctly.", + "questions": [ + { + "question": "What happens on the last line?", + "code": "class Employee:\n def __init__(self, name):\n self.name = name\n\nclass Manager(Employee):\n def __init__(self, name, team_size):\n self.team_size = team_size\n\nboss = Manager(\"Dilnoza\", 5)\nprint(boss.name)", + "options": [ + "It prints Dilnoza", + "It prints None", + "AttributeError", + "TypeError" + ], + "answer": 2, + "explanation": "Defining __init__ in the child replaces the parent's, so self.name is never set. Call super().__init__(name) first.", + "lesson": "inheritance" + }, + { + "question": "Which hint says that scores is a list of integers or None?", + "options": [ + "scores: list[int] | None", + "scores: List[int, None]", + "scores: list | None[int]", + "scores: Optional(list[int])" + ], + "answer": 0, + "explanation": "On modern Python, list[int] is the built-in generic and X | None means 'X or None'. Optional[X] from typing is the older spelling of the same thing.", + "lesson": "type-hints" + }, + { + "question": "What happens when this code runs?", + "code": "from abc import ABC, abstractmethod\nclass Shape(ABC):\n @abstractmethod\n def area(self): ...\nclass Square(Shape):\n def __init__(self, side):\n self.side = side\n def Area(self):\n return self.side ** 2\nprint(Square(3).Area())", + "options": [ + "It prints 9", + "It prints None", + "TypeError", + "AttributeError" + ], + "answer": 2, + "explanation": "Area with a capital A is a different name, so area is still abstract and the ABC refuses to create a Square.", + "lesson": "polymorphism-and-abcs" + }, + { + "question": "An Order class needs to write log messages using a Logger class. Which design is best?", + "options": [ + "class Order(Logger): inherit from it", + "Give Order a logger attribute", + "Copy the log method into Order", + "class Logger(Order): make Logger a child" + ], + "answer": 1, + "explanation": "An order is not a logger, so it fails the is-a test. An order has a logger, which is composition.", + "lesson": "composition" + }, + { + "question": "What happens on the last line?", + "code": "from dataclasses import dataclass, field\n\n@dataclass(frozen=True)\nclass Point:\n x: int\n tags: list = field(default_factory=list)\n\np = Point(1)\np.x = 5", + "options": [ + "It sets p.x to 5", + "FrozenInstanceError", + "TypeError", + "It creates a new Point" + ], + "answer": 1, + "explanation": "frozen=True makes the dataclass immutable: assigning to a field raises dataclasses.FrozenInstanceError. field(default_factory=list) gives each instance its own list.", + "lesson": "dataclasses" + }, + { + "question": "What does this code print?", + "code": "from dataclasses import dataclass\n\n@dataclass\nclass Book:\n title: str\n pages = 100\n\nprint(Book(\"Days Gone By\"))", + "options": [ + "Book(title='Days Gone By', pages=100)", + "TypeError", + "Book(title='Days Gone By')", + "Book('Days Gone By')" + ], + "answer": 2, + "explanation": "Without an annotation, pages is only a class attribute, not a field, so it is missing from __init__ and the repr.", + "lesson": "dataclasses" + }, + { + "question": "What does this code print?", + "code": "from dataclasses import dataclass, field\n\n@dataclass(order=True)\nclass Score:\n points: int\n name: str = field(compare=False)\n\nscores = [Score(90, \"Aziza\"), Score(75, \"Bekzod\"), Score(90, \"Anvar\")]\nprint(max(scores).name, Score(90, \"X\") == Score(90, \"Y\"))", + "options": [ + "Aziza True", + "Anvar True", + "Aziza False", + "TypeError" + ], + "answer": 0, + "explanation": "With compare=False, only points is compared. Two scores tie at 90, and max() returns the first one it finds.", + "lesson": "dataclasses" + }, + { + "question": "What does this code print?", + "code": "from enum import Enum\n\nclass Status(Enum):\n PAID = \"paid\"\n\nstatus = Status(\"paid\")\nprint(status == \"paid\", status is Status.PAID)", + "options": [ + "True True", + "True False", + "False False", + "False True" + ], + "answer": 3, + "explanation": "A plain Enum member is never equal to its raw value. Status(\"paid\") looks up the member, so the is check is True.", + "lesson": "enums" + }, + { + "question": "What does this code print?", + "code": "from enum import Enum\n\nclass Size(Enum):\n SMALL = \"S\"\n LARGE = \"L\"\n\nprint(Size[\"SMALL\"].value, Size(\"L\").name)", + "options": [ + "SMALL L", + "S LARGE", + "S L", + "ValueError" + ], + "answer": 1, + "explanation": "Square brackets look up by name and parentheses by value. .value gives \"S\" and .name gives \"LARGE\".", + "lesson": "enums" + }, + { + "question": "The hint says list[int], but a tuple is passed. What happens?", + "code": "def average(scores: list[int]) -> float:\n return sum(scores) / len(scores)\n\nprint(average((80, 90)))", + "options": [ + "TypeError", + "It prints 85", + "A type checker error stops the program", + "It prints 85.0" + ], + "answer": 3, + "explanation": "Type hints are not checked at runtime, so the tuple works fine. Only a separate type checker would complain.", + "lesson": "type-hints" + } + ] +} diff --git a/docs/.vitepress/quizzes/module-11.json b/docs/.vitepress/quizzes/module-11.json new file mode 100644 index 0000000..c9dfc72 --- /dev/null +++ b/docs/.vitepress/quizzes/module-11.json @@ -0,0 +1,132 @@ +{ + "module": "11 · Testing and Debugging", + "title": "Checkpoint: Testing and Debugging", + "intro": "Check that you can write useful tests, pick good test cases, use pytest, and debug with print, tracebacks, and logging.", + "questions": [ + { + "question": "What happens when this code runs?", + "code": "price = 15000\nassert(price == 20000, \"wrong price\")\nprint(\"passed?\")", + "options": [ + "AssertionError: wrong price", + "It prints passed? (with a SyntaxWarning)", + "SyntaxError", + "Nothing is printed" + ], + "answer": 1, + "explanation": "The parentheses make a non-empty tuple, which is always true, so the assert never fails. Write assert price == 20000, \"wrong price\".", + "lesson": "testing-with-assert" + }, + { + "question": "Which assertion passes for 0.1 + 0.2?", + "options": [ + "assert 0.1 + 0.2 == pytest.approx(0.3)", + "assert 0.1 + 0.2 == 0.3", + "assert round(0.1 + 0.2) == 0.3", + "assert 0.1 + 0.2 is 0.3" + ], + "answer": 0, + "explanation": "0.1 + 0.2 is 0.30000000000000004, so == 0.3 fails. pytest.approx (or math.isclose) compares with a tolerance.", + "lesson": "pytest-basics" + }, + { + "question": "This prints False. What is the best way to test the average?", + "code": "average = (0.1 + 0.2 + 0.3) / 3\nprint(average == 0.2)", + "options": [ + "assert math.isclose(average, 0.2)", + "assert average == 0.20000000000000004", + "assert int(average) == 0", + "assert str(average) == \"0.2\"" + ], + "answer": 0, + "explanation": "Floats have tiny rounding errors, so compare them with math.isclose() (or pytest.approx in pytest).", + "lesson": "testing-with-assert" + }, + { + "question": "A registration form must reject negative ages. Which is correct?", + "options": [ + "assert age >= 0 in the form handler", + "print(\"bad\") when age is below 0", + "raise ValueError when age is below 0", + "wrap assert age >= 0 in try/except: pass" + ], + "answer": 2, + "explanation": "assert statements are removed when Python runs with -O, so real validation needs if and raise.", + "lesson": "testing-with-assert" + }, + { + "question": "A function gives a discount for orders of 100000 som or more. Which set of test values is best?", + "options": [ + "50000, 60000, 70000", + "99999, 100000, 100001", + "100000 only", + "200000, 300000" + ], + "answer": 1, + "explanation": "Bugs hide at boundaries. Testing just below, at, and just above the limit catches mistakes like > instead of >=.", + "lesson": "choosing-test-cases" + }, + { + "question": "Which test is better for tax(price) = price * 12 // 100?", + "options": [ + "assert tax(15000) == 15000 * 12 // 100", + "assert tax(15000) > 0", + "assert tax(15000) is not None", + "assert tax(15000) == 1800" + ], + "answer": 3, + "explanation": "An expected value copied from the code repeats its bugs. Use a plain number you worked out by hand.", + "lesson": "choosing-test-cases" + }, + { + "question": "You run pytest in a folder with totals.py containing def check_total(). pytest says \"collected 0 items\". Why?", + "options": [ + "pytest is not installed in this project", + "Test files and functions must be named test_*", + "The assert inside the function is wrong", + "Tests must be inside a TestCase class" + ], + "answer": 1, + "explanation": "pytest only collects files and functions whose names start with test. \"no tests ran\" is not success.", + "lesson": "pytest-basics" + }, + { + "question": "pytest runs this test. What is the result?", + "code": "import pytest\ndef withdraw(balance, amount):\n if amount > balance:\n raise ValueError(\"not enough\")\n return balance - amount\ndef test_too_much():\n balance = 100\n with pytest.raises(ValueError):\n balance = withdraw(balance, 500)\n assert balance == 999\n", + "options": [ + "It passes, but the assert is never checked", + "It fails because balance is not 999", + "It fails with ValueError", + "pytest reports an error in the test" + ], + "answer": 0, + "explanation": "withdraw() raises inside the with block, so the next line never runs. Put checks after the with block.", + "lesson": "pytest-basics" + }, + { + "question": "What appears on the screen when this script runs?", + "code": "import logging\nlogging.info(\"order created\")\nlogging.warning(\"stock low\")", + "options": [ + "INFO:root:order created", + "Both messages", + "Nothing", + "WARNING:root:stock low" + ], + "answer": 3, + "explanation": "Without basicConfig the level is WARNING, so info() messages are dropped.", + "lesson": "debugging-and-logging" + }, + { + "question": "What does this code print?", + "code": "x = 7\nitems = [\"tea\", \"bread\"]\nprint(f\"{x=} {len(items)=}\")", + "options": [ + "7 2", + "x=7 len(items)=2", + "{x=} {len(items)=}", + "x = 7, len(items) = 2" + ], + "answer": 1, + "explanation": "The = inside an f-string field prints the expression text followed by its value, which is handy for print debugging.", + "lesson": "debugging-and-logging" + } + ] +} diff --git a/docs/.vitepress/quizzes/module-12.json b/docs/.vitepress/quizzes/module-12.json new file mode 100644 index 0000000..045f1b4 --- /dev/null +++ b/docs/.vitepress/quizzes/module-12.json @@ -0,0 +1,136 @@ +{ + "module": "12 · Going Further", + "title": "Checkpoint: Going Further", + "intro": "Check that you understand iterators, generators, and regular expressions, and how to structure a text-processing program.", + "questions": [ + { + "question": "What do the two print calls show?", + "code": "evens = (n for n in range(10) if n % 2 == 0)\nprint(sum(evens))\nprint(sum(evens))", + "options": [ + "20, then 20", + "20, then 0", + "20, then an error", + "0, then 20" + ], + "answer": 1, + "explanation": "The first sum() exhausts the generator, so the second one sees no values and returns 0.", + "lesson": "iterators-and-generators" + }, + { + "question": "What lines are printed, in order?", + "code": "def countdown(n):\n print(\"start\")\n while n > 0:\n yield n\n n -= 1\n\ngen = countdown(3)\nprint(\"created\")\nprint(next(gen), next(gen))", + "options": [ + "start, created, 3 2", + "created, 3 2", + "created, start, 3 2", + "start, 3 2, created" + ], + "answer": 2, + "explanation": "Calling a generator function only creates the generator. The body starts running at the first next().", + "lesson": "iterators-and-generators" + }, + { + "question": "What happens when this code runs?", + "code": "cities = [\"Tashkent\", \"Bukhara\"]\nprint(next(cities))", + "options": [ + "It prints Tashkent", + "StopIteration", + "It prints ['Tashkent', 'Bukhara']", + "TypeError" + ], + "answer": 3, + "explanation": "A list is iterable but not an iterator. Use next(iter(cities)).", + "lesson": "iterators-and-generators" + }, + { + "question": "What does this code print?", + "code": "def chunks():\n yield from [1, 2]\n yield 3\n\nprint(list(chunks()), sum(chunks()))", + "options": [ + "[1, 2, 3] 6", + "[[1, 2], 3] 6", + "[1, 2, 3] 0", + "TypeError" + ], + "answer": 0, + "explanation": "yield from produces each item of the list one by one. Each call to chunks() makes a fresh generator, so sum() sees all values.", + "lesson": "iterators-and-generators" + }, + { + "question": "What does this code print?", + "code": "import re\ntext = \"Total: 45000 som\"\nprint(re.match(r\"\\d+\", text))", + "options": [ + "45000", + "None", + "", + "[]" + ], + "answer": 1, + "explanation": "re.match only checks the start of the string, which is not a digit. Use re.search to look anywhere.", + "lesson": "regular-expressions" + }, + { + "question": "What does this code print?", + "code": "import re\nhtml = \"Plov and Somsa\"\nprint(re.findall(r\"(.*)\", html))", + "options": [ + "['Plov', 'Somsa']", + "['Plov', 'Somsa']", + "['Plov and Somsa']", + "[]" + ], + "answer": 2, + "explanation": "Greedy .* grabs as much as possible, up to the last . Use .*? or [^<]* to stop at the first one.", + "lesson": "regular-expressions" + }, + { + "question": "What does this code print?", + "code": "import re\nprint(bool(re.match(r\"\\d+\", \"123abc\")), bool(re.fullmatch(r\"\\d+\", \"123abc\")))", + "options": [ + "True False", + "True True", + "False False", + "False True" + ], + "answer": 0, + "explanation": "match succeeds because the string starts with digits, but fullmatch requires the whole string to match. Use fullmatch for validation.", + "lesson": "regular-expressions" + }, + { + "question": "What does this code print?", + "code": "import re\nm = re.search(r\"(?P\\d{2})\\.(?P\\d{2})\", \"Date: 15.09.2026\")\nprint(m.group(\"month\"), m.group(0))", + "options": [ + "15 09", + "09 15", + "09 15.09", + "15.09 09" + ], + "answer": 2, + "explanation": "Named groups are read by name, and group(0) is the whole match.", + "lesson": "regular-expressions" + }, + { + "question": "What does this code print?", + "code": "from collections import Counter\ntext = \"Plov, plov and more plov!\"\nprint(Counter(text.lower().split())[\"plov\"])", + "options": [ + "3", + "0", + "KeyError", + "1" + ], + "answer": 3, + "explanation": "split() leaves punctuation attached, so \"plov,\" and \"plov!\" count as different words. Extract words with a regex like [a-z]+.", + "lesson": "text-processing-project" + }, + { + "question": "In the text analyzer, where should functions like count_sentences(text) get their data, and where should printing happen?", + "options": [ + "Take text as an argument and return values", + "Read the file and print inside each function", + "Store text and results in global variables", + "Put everything in one main() function" + ], + "answer": 0, + "explanation": "Pure functions that take arguments and return values are easy to test and reuse. Keep file reading and printing at the edges.", + "lesson": "text-processing-project" + } + ] +} diff --git a/docs/.vitepress/quizzes/module-13.json b/docs/.vitepress/quizzes/module-13.json new file mode 100644 index 0000000..de22383 --- /dev/null +++ b/docs/.vitepress/quizzes/module-13.json @@ -0,0 +1,136 @@ +{ + "module": "13 · Working with Data (Optional)", + "title": "Checkpoint: Working with Data", + "intro": "Check that you can load and filter tables with pandas, summarize them, and draw clear charts with matplotlib.", + "questions": [ + { + "question": "What does this code print?", + "code": "import pandas as pd\ndf = pd.DataFrame({\"city\": [\"Tashkent\", \"Bukhara\", \"Samarkand\"],\n \"temp\": [31.5, 28.1, 33.0]})\nprint(df.iloc[1][\"city\"], df.loc[2, \"temp\"])", + "options": [ + "Tashkent 33.0", + "Bukhara 28.1", + "Bukhara 33.0", + "KeyError" + ], + "answer": 2, + "explanation": ".iloc selects by position (row 1 is Bukhara), and .loc selects by label (index 2 is Samarkand's row).", + "lesson": "reading-data" + }, + { + "question": "What happens when this code runs?", + "code": "import pandas as pd\ndf = pd.DataFrame({\"city\": [\"Tashkent\", \"Bukhara\"], \"temp\": [31.5, 28.1]})\nprint(df[\"city\", \"temp\"])", + "options": [ + "KeyError", + "It prints both columns", + "It prints only the city column", + "ValueError" + ], + "answer": 0, + "explanation": "Single brackets look for one column named by the tuple (\"city\", \"temp\"). Pass a list: df[[\"city\", \"temp\"]].", + "lesson": "reading-data" + }, + { + "question": "What does this code print?", + "code": "import pandas as pd\n\norders = pd.DataFrame({\"product\": [\"Tea\", \"Halva\"], \"qty\": [2, 1]})\nprices = pd.DataFrame({\"product\": [\"Tea\"], \"price\": [15000]})\nprint(len(orders.merge(prices, on=\"product\")), len(orders.merge(prices, on=\"product\", how=\"left\")))", + "options": [ + "1 2", + "2 2", + "2 1", + "KeyError" + ], + "answer": 0, + "explanation": "An inner merge keeps only products found in both tables (Tea). A left merge keeps every order and fills the missing price with NaN.", + "lesson": "pandas-basics" + }, + { + "question": "What happens when this code runs?", + "code": "import pandas as pd\ndf = pd.DataFrame({\"temp\": [31.5, 28.1], \"humidity\": [22, 30]})\nprint(df[df[\"temp\"] > 30 and df[\"humidity\"] < 25])", + "options": [ + "It prints the Tashkent row", + "ValueError", + "It prints an empty DataFrame", + "KeyError" + ], + "answer": 1, + "explanation": "and needs a single True or False, but each comparison gives a whole Series. Use & with parentheses around each condition.", + "lesson": "reading-data" + }, + { + "question": "What does this code print?", + "code": "import pandas as pd\nsales = pd.DataFrame({\"city\": [\"Tashkent\", \"Bukhara\", \"Tashkent\"],\n \"quantity\": [4, 12, 6]})\nprint(sales.groupby(\"city\")[\"quantity\"].sum()[\"Tashkent\"])", + "options": [ + "2", + "4", + "10", + "22" + ], + "answer": 2, + "explanation": "groupby collects the rows for each city, and sum() adds Tashkent's quantities: 4 + 6.", + "lesson": "pandas-basics" + }, + { + "question": "What does this code print?", + "code": "import pandas as pd\nsales = pd.DataFrame({\"product\": [\"tea\", \"plov\", \"tea\", \"tea\"]})\ncounts = sales[\"product\"].value_counts()\nprint(counts.index[0], counts.iloc[0])", + "options": [ + "tea 3", + "plov 1", + "tea 1", + "product 4" + ], + "answer": 0, + "explanation": "value_counts() counts each value and sorts from most to least common, so tea with 3 comes first.", + "lesson": "pandas-basics" + }, + { + "question": "What does this code print?", + "code": "import pandas as pd\ndf = pd.DataFrame({\"name\": [\" aziza\", \"BEKZOD \"]})\nprint(df[\"name\"].str.strip().str.title().tolist())", + "options": [ + "[' aziza', 'BEKZOD ']", + "AttributeError", + "['aziza', 'bekzod']", + "['Aziza', 'Bekzod']" + ], + "answer": 3, + "explanation": "The .str accessor applies string methods to every value in the column, and they can be chained.", + "lesson": "pandas-basics" + }, + { + "question": "What does the print show?", + "code": "import pandas as pd\nsales = pd.DataFrame({\"city\": [\"Tashkent\", \"Bukhara\"], \"price\": [15000, 8000]})\nsales[sales[\"city\"] == \"Bukhara\"][\"price\"] = 9000\nprint(sales.loc[1, \"price\"])", + "options": [ + "9000", + "8000", + "KeyError", + "None" + ], + "answer": 1, + "explanation": "Chained indexing assigns into a temporary copy, so the original is unchanged. Use sales.loc[sales[\"city\"] == \"Bukhara\", \"price\"] = 9000.", + "lesson": "pandas-basics" + }, + { + "question": "What happens on the last line?", + "code": "import matplotlib\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\nfig, ax = plt.subplots()\nax.title(\"Sales\")", + "options": [ + "The title is set to Sales", + "AttributeError", + "TypeError", + "Nothing until plt.show()" + ], + "answer": 2, + "explanation": "ax.title is a Text object, not a method. On an Axes use ax.set_title(\"Sales\").", + "lesson": "charts-with-matplotlib" + }, + { + "question": "You want to see how daily temperatures are distributed across a year. Which chart fits best?", + "options": [ + "A pie chart", + "A histogram", + "A line chart of the months' names", + "A scatter plot with one point" + ], + "answer": 1, + "explanation": "A histogram groups values into bins and shows how often each range occurs, which is exactly a distribution.", + "lesson": "charts-with-matplotlib" + } + ] +} diff --git a/docs/.vitepress/quizzes/module-14.json b/docs/.vitepress/quizzes/module-14.json new file mode 100644 index 0000000..252e2a9 --- /dev/null +++ b/docs/.vitepress/quizzes/module-14.json @@ -0,0 +1,158 @@ +{ + "module": "14 · Advanced Python (Optional)", + "title": "Checkpoint: Advanced Python", + "intro": "Check that you understand decorators, the data model, context managers, and async code, and how Python handles memory, patterns, concurrency, and testing.", + "questions": [ + { + "question": "What does city(\"Bukhara\") return?", + "code": "def bold(func):\n return lambda text: \"\" + func(text) + \"\"\ndef italic(func):\n return lambda text: \"\" + func(text) + \"\"\n@italic\n@bold\ndef city(name): return name", + "options": [ + "\"Bukhara\"", + "\"Bukhara\"", + "\"Bukhara\"", + "\"Bukhara\"" + ], + "answer": 2, + "explanation": "Stacked decorators are applied bottom-up, so city = italic(bold(city)). The top decorator, italic, is the outermost wrapper.", + "lesson": "closures-and-decorators" + }, + { + "question": "Which line does @retry(times=3) above def fetch_rate() mean?", + "options": [ + "fetch_rate = retry(fetch_rate, times=3)", + "fetch_rate = retry(times=3)(fetch_rate)", + "fetch_rate = retry(times=3)", + "fetch_rate = retry(fetch_rate)(times=3)" + ], + "answer": 1, + "explanation": "retry(times=3) runs first and must return a decorator, which is then called with the function. That is why a decorator with arguments needs one more level of nesting.", + "lesson": "closures-and-decorators" + }, + { + "question": "What does this code print?", + "code": "class Settings:\n language = \"uz\"\n def __getattr__(self, name):\n return f\"<{name}>\"\ns = Settings()\nprint(s.language, s.theme)", + "options": [ + "uz ", + " ", + "uz, then AttributeError", + ", then AttributeError" + ], + "answer": 0, + "explanation": "__getattr__ is only a fallback: language is found on the class by normal lookup, and only the missing theme goes to __getattr__.", + "lesson": "python-data-model" + }, + { + "question": "When does a parent class's __init_subclass__ run?", + "options": [ + "Each time an instance of a subclass is created", + "Only when a subclass calls super().__init__()", + "The first time a method of the subclass is called", + "When the subclass itself is defined" + ], + "answer": 3, + "explanation": "__init_subclass__ runs as soon as a class statement creates a subclass, with the new class as cls, which is why it suits plugin registries.", + "lesson": "python-data-model" + }, + { + "question": "What lines are printed, in order?", + "code": "from contextlib import ExitStack\nwith ExitStack() as stack:\n stack.callback(print, \"first\")\n stack.callback(print, \"second\")\n print(\"body\")", + "options": [ + "first, second, body", + "body, second, first", + "body, first, second", + "second, first, body" + ], + "answer": 1, + "explanation": "Callbacks run when the with block ends, not when they are registered, and ExitStack runs them in reverse order.", + "lesson": "context-managers-in-depth" + }, + { + "question": "Which statement about a class-based context manager is true?", + "options": [ + "__exit__ is still called if __enter__ raises an exception", + "If __exit__ returns None, the exception from the block is swallowed", + "If __exit__ returns a true value, the exception from the block is swallowed", + "__exit__ receives three Nones when the block raised an exception" + ], + "answer": 2, + "explanation": "A true return value from __exit__ swallows the exception; None or False lets it propagate. The three Nones mean the block finished normally.", + "lesson": "context-managers-in-depth" + }, + { + "question": "What does this code print?", + "code": "async def fetch(city):\n return f\"{city}: 12,650 som\"\nasync def main():\n result = fetch(\"Tashkent\")\n print(type(result).__name__)\nawait main()", + "options": [ + "coroutine", + "Tashkent: 12,650 som", + "str", + "NoneType" + ], + "answer": 0, + "explanation": "Calling an async def function only creates a coroutine object; its body runs when you await it. Python also warns that the coroutine was never awaited.", + "lesson": "async-await" + }, + { + "question": "What does this code print?", + "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(\"Bukhara\", 0.3), fetch(\"Tashkent\", 0.1)))\nawait main()", + "options": [ + "['Tashkent', 'Bukhara']", + "Tashkent", + "It depends on which request finishes first", + "['Bukhara', 'Tashkent']" + ], + "answer": 3, + "explanation": "Tashkent finishes first, but gather returns the results in the order you passed the coroutines, not the order they finish.", + "lesson": "async-await" + }, + { + "question": "What does this code print?", + "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 measures only the list object itself. A list stores references to its items, so the size of the strings is not included.", + "lesson": "memory-and-performance" + }, + { + "question": "What does this code print?", + "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 is a class attribute, so shop and bank append to the same list. Create the list in __init__ with self.listeners = [] to give each emitter its own.", + "lesson": "design-patterns" + }, + { + "question": "A pure-Python function counts primes, and you want to run it on two large inputs at the same time with the normal CPython build. Which tool actually uses two CPU cores?", + "options": [ + "ProcessPoolExecutor", + "ThreadPoolExecutor", + "asyncio.gather", + "Two threading.Thread objects with a Lock" + ], + "answer": 0, + "explanation": "Because of the GIL, only one thread runs Python code at a time, and asyncio runs in one thread. Each process has its own interpreter and GIL.", + "lesson": "threads-and-processes" + }, + { + "question": "prices.py does from rates import fetch_rate and then calls fetch_rate(). In a test of prices.price_in_som, which patch replaces the rate lookup?", + "options": [ + "patch(\"rates.fetch_rate\")", + "patch(\"fetch_rate\")", + "patch(\"rates.prices.fetch_rate\")", + "patch(\"prices.fetch_rate\")" + ], + "answer": 3, + "explanation": "The import creates a second name, fetch_rate, inside prices. Patch the name where the code looks it up, not where it is defined.", + "lesson": "testing-in-depth" + } + ] +} diff --git a/docs/.vitepress/quizzes/uz/module-01.json b/docs/.vitepress/quizzes/uz/module-01.json new file mode 100644 index 0000000..2465d28 --- /dev/null +++ b/docs/.vitepress/quizzes/uz/module-01.json @@ -0,0 +1,134 @@ +{ + "module": "01 · Kiriş", + "title": "Nazorat: Kiriş", + "intro": "Pythonni işga tuşira olişingiz, matn çop etişingiz va dastlab uçraydigan xato xabarlarini öqiy olişingizni tekşiring.", + "questions": [ + { + "question": "Bu kod nimani çop etadi?", + "code": "print(\"Hello\", \"Aziza\", sep=\"-\")", + "options": [ + "Hello-Aziza", + "Hello Aziza", + "Hello-Aziza-", + "HelloAziza" + ], + "answer": 0, + "explanation": "sep qiymatlar orasiga nima qöyilişini belgilaydi, şuning uçun print odatdagi böşliq örniga çiziqça qöyadi.", + "lesson": "hello-world" + }, + { + "question": "Bu qatorni işga tuşirganda nima böladi?", + "code": "Print(\"Salom\")", + "options": [ + "Salom ni çop etadi", + "SyntaxError", + "NameError", + "TypeError" + ], + "answer": 2, + "explanation": "Python harflarning katta-kiçikligini farqlaydi. Faqat print mavjud, şuning uçun Print notaniş nom va NameError çaqiradi.", + "lesson": "what-is-python" + }, + { + "question": "Oynangizda >>> körinib turibdi, siz python hello.py deb yozasiz va SyntaxError olasiz. Nima notöğri?", + "options": [ + "hello.py fayli böş, şuning uçun işga tuşadigan narsa yöq", + "Siz Python REPL içidasiz: exit() deb yozing, keyin buyruqni terminalda bering", + "Faylni işga tuşiriş uçun print(python hello.py) deb yoziş kerak", + "Python örnatilmagan, şuning uçun buyruq tanilmaydi" + ], + "answer": 1, + "explanation": ">>> taklif belgisi siz allaqaçon Python içida ekaningizni bildiradi, u yerda faqat Python kodi işlaydi. Terminal buyruqlari $ yoki PS taklif belgisida yoziladi.", + "lesson": "install-and-setup" + }, + { + "question": "Skript faylida faqat quyidagi qator bor. Uni python3 sum.py bilan işga tuşirasiz. Nimani körasiz?", + "code": "2 + 3", + "options": [ + "5", + "2 + 3", + "Xato xabarini", + "Heç narsani" + ], + "answer": 3, + "explanation": "Skriptlar REPL kabi qiymatlarni avtomatik körsatmaydi. Qiymatni köriş uçun ifodani print() içiga oling.", + "lesson": "running-python" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "print(\"Tashkent\", end=\"!\")\nprint(\"Samarkand\")", + "options": [ + "Tashkent! Samarkand", + "TashkentSamarkand!", + "Tashkent!Samarkand", + "SyntaxError" + ], + "answer": 2, + "explanation": "end=\"!\" odatdagi yangi qatorni ! bilan almaştiradi, şuning uçun keyingi print öşa qatorda davom etadi.", + "lesson": "hello-world" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "print(\"7 * 3 =\", 7 * 3)", + "options": [ + "7 * 3 = 21", + "21 = 21", + "7 * 3 = 7 * 3", + "7 * 3 =21" + ], + "answer": 0, + "explanation": "Qöştirnoq içidagi qism matn bölib, qanday bölsa şunday çop etiladi; qöştirnoqsiz qism hisoblanadi. print ular orasiga böşliq qöyadi.", + "lesson": "hello-world" + }, + { + "question": "Qaysi izoh eng foydali?", + "options": [ + "count = count + 1 # count ga 1 qöşamiz", + "print(total) # jami qiymatni çop etamiz", + "x = 5 # x ni beşga tenglaymiz", + "tax_rate = 0.12 # QQS stavkasi; har yili tekşiring" + ], + "answer": 3, + "explanation": "Yaxşi izohlar nega ekanini tuşuntiradi yoki kod körsata olmaydigan kontekstni beradi. Qolganlari kod allaqaçon aytgan narsani takrorlaydi.", + "lesson": "comments-and-style" + }, + { + "question": "Bu dastur nega xato beradi?", + "code": "print(\"start\")\n print(\"next\")", + "options": [ + "print oxirida ikki nuqta bölişi kerak", + "Ikkinçi qator sababsiz çekiniş bilan yozilgan", + "Satrlarda böşliq bölişi mumkin emas", + "print ni ikki marta çaqirib bölmaydi" + ], + "answer": 1, + "explanation": "Faqat blok içidagi kod (masalan, if tanasi) çekiniş bilan yozilişi kerak. Ortiqça böşliqlar IndentationError: unexpected indent xatosini keltirib çiqaradi.", + "lesson": "comments-and-style" + }, + { + "question": "macOS yoki Linux terminalida interaktiv Python qobiğini (REPL) qaysi buyruq oçadi?", + "options": [ + "python3", + "python3 hello.py", + "py --version", + "pip3 python" + ], + "answer": 0, + "explanation": "Fayl nomisiz python3 REPL ni işga tuşiradi, unda >>> belgisini körasiz. python3 hello.py esa faylni işga tuşiradi.", + "lesson": "running-python" + }, + { + "question": "REPL da quyidagi qatorni yozib Enter bosdingiz. Hiç narsa çiqmadi. Nega?", + "code": "total = 120 + 80", + "options": [ + "Qiymat berişning körsatadigan qiymati yöq; REPL faqat ifodalarni aks ettiradi", + "Python hali ikkinçi kiritiş qatorini kutmoqda", + "total nomi band, şuning uçun u eʼtiborsiz qoldirildi", + "REPL print() çaqirilmagunça hiç narsa körsatmaydi" + ], + "answer": 0, + "explanation": "REPL total yoki 2 + 3 kabi ifodaning qiymatini körsatadi, qiymat beriş esa qiymat bermaydi, şuning uçun hiç narsa çiqmaydi.", + "lesson": "running-python" + } + ] +} diff --git a/docs/.vitepress/quizzes/uz/module-02.json b/docs/.vitepress/quizzes/uz/module-02.json new file mode 100644 index 0000000..80f8a50 --- /dev/null +++ b/docs/.vitepress/quizzes/uz/module-02.json @@ -0,0 +1,136 @@ +{ + "module": "02 · Özgaruvçilar va maʼlumot turlari", + "title": "Nazorat: Özgaruvçilar va maʼlumot turlari", + "intro": "Özgaruvçilar, sonlar, satrlar, f-satrlar, kiritiş va xatolarni öqiş böyiça bilimingizni sinab köring.", + "questions": [ + { + "question": "Bu kod nimani çop etadi?", + "code": "x = 5\ny = x\nx = 10\nprint(y)", + "options": [ + "5", + "10", + "15", + "NameError" + ], + "answer": 0, + "explanation": "y = x y ni 5 qiymatiga işora qildiradi. Keyinroq x ga yangi qiymat beriş y ni özgartirmaydi.", + "lesson": "variables" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "print(7 // 2, 7 % 2)", + "options": [ + "3.5 1", + "4 1", + "3 1", + "3 0.5" + ], + "answer": 2, + "explanation": "// bölişning butun qismini (3), % esa qoldiqni (1) beradi.", + "lesson": "numbers-and-math" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "print(10 / 2, 10 // 2)", + "options": [ + "5 5", + "5.0 5", + "5.0 5.0", + "5 5.0" + ], + "answer": 1, + "explanation": "/ har doim float beradi, hatto bölinma butun bölsa ham. // ikkala tomon int bölganda int beradi.", + "lesson": "numbers-and-math" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "word = \"Tashkent\"\nprint(word[-1], word[0:4])", + "options": [ + "n Tashk", + "t Tashk", + "T Tash", + "t Tash" + ], + "answer": 3, + "explanation": "-1 indeksi oxirgi belgi, kesim esa stop indeksidan oldin töxtaydi, şuning uçun [0:4] birinçi 4 ta belgini beradi.", + "lesson": "string-methods-and-slicing" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "city = \"tashkent\"\ncity.capitalize()\nprint(city)", + "options": [ + "Tashkent", + "TASHKENT", + "tashkent", + "None" + ], + "answer": 2, + "explanation": "Satr metodlari yangi satr qaytaradi; ular heç qaçon aslini özgartirmaydi. Natijani saqlang: city = city.capitalize().", + "lesson": "string-methods-and-slicing" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "price = 12500.5\nprint(f\"{price:,.2f} som\")", + "options": [ + "12,500.50 som", + "12,500.5 som", + "12500.50 som", + "12,501 som" + ], + "answer": 0, + "explanation": ", minglik ajratuvçisini qöşadi, .2f esa aynan ikki önlik xonani körsatadi.", + "lesson": "f-strings" + }, + { + "question": "Foydalanuvçi 20 ni kiritadi. Bu kod nimani çop etadi?", + "code": "age = input(\"Age: \")\nprint(age * 2)", + "options": [ + "40", + "TypeError", + "20 20", + "2020" + ], + "answer": 3, + "explanation": "input() doim satr qaytaradi, satrni 2 ga köpaytiriş esa uni takrorlaydi. Avval int(input(...)) bilan özgartiring.", + "lesson": "type-conversion-and-input" + }, + { + "question": "Bu kodni işga tuşirganda nima böladi?", + "code": "total = 100\nprint(\"Total: \" + total)", + "options": [ + "Total: 100 ni çop etadi", + "TypeError", + "ValueError", + "NameError" + ], + "answer": 1, + "explanation": "Python satr va int ni avtomatik birlaştirmaydi. str(total) yoki f-satrdan foydalaning.", + "lesson": "strings-basics" + }, + { + "question": "Bu kodni işga tuşirganda nima böladi?", + "code": "price = int(\"12.5\")\nprint(price)", + "options": [ + "12", + "12.5", + "ValueError", + "TypeError" + ], + "answer": 2, + "explanation": "int() önlik nuqtali matnni öqiy olmaydi. Qiymat önlik bölişi mumkin bölsa, float() dan foydalaning.", + "lesson": "type-conversion-and-input" + }, + { + "question": "Ekraningizda uzun traceback paydo böldi. Birinçi navbatda qayerga qaraş kerak?", + "options": [ + "Birinçi qator, Traceback (most recent call last):", + "Xatoni nomlaydigan va tasvirlaydigan oxirgi qator", + "Faqat örtadagi qatorlar", + "Heç qayerga; kod işlagunça uni özgartiraveriş" + ], + "answer": 1, + "explanation": "Foydali maʼlumot pastda: xato turi va xabari. Yuqoridagi qatorlar xato qayerda sodir bölganini körsatadi.", + "lesson": "reading-errors-and-debugging" + } + ] +} diff --git a/docs/.vitepress/quizzes/uz/module-03.json b/docs/.vitepress/quizzes/uz/module-03.json new file mode 100644 index 0000000..111ad64 --- /dev/null +++ b/docs/.vitepress/quizzes/uz/module-03.json @@ -0,0 +1,136 @@ +{ + "module": "03 · Şart operatorlari", + "title": "Nazorat: Şart operatorlari", + "intro": "Qiymatlarni taqqoslaş, şartlarni birlaştiriş va if hamda match yordamida tarmoqlar orasidan tanlaş qançalik yaxşi çiqişini tekşiring.", + "questions": [ + { + "question": "Bu kod nimani çop etadi?", + "code": "answer = \"7\"\nprint(answer == 7)", + "options": [ + "False", + "True", + "7", + "TypeError" + ], + "answer": 0, + "explanation": "\"7\" satr, 7 esa son, şuning uçun ular heç qaçon teng bölmaydi. Taqqoslaşdan oldin int(answer) bilan özgartiring.", + "lesson": "booleans-and-comparisons" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "print(bool(\"\"), bool(\"0\"))", + "options": [ + "False False", + "True True", + "False True", + "True False" + ], + "answer": 2, + "explanation": "Böş satr yolğon hisoblanadi, lekin har qanday böş bölmagan satr, hatto \"0\" ham, rost hisoblanadi.", + "lesson": "booleans-and-comparisons" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "print(1 < 5 < 3)", + "options": [ + "True", + "False", + "SyntaxError", + "3" + ], + "answer": 1, + "explanation": "Zanjirli taqqoslaş 1 < 5 and 5 < 3 degani. Ikkinçi qism False, şuning uçun butun ifoda False.", + "lesson": "booleans-and-comparisons" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "temp = 30\nif temp > 10:\n print(\"Warm\")\nelif temp > 20:\n print(\"Hot\")\nelse:\n print(\"Cold\")", + "options": [ + "Hot", + "Hot and Warm", + "Cold", + "Warm" + ], + "answer": 3, + "explanation": "Python şartlarni yuqoridan pastga tekşiradi va faqat birinçi rost tarmoqni bajaradi. 30 > 10 rost, şuning uçun Hot tekşiruviga heç qaçon yetib kelmaydi.", + "lesson": "if-elif-else" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "answer = \"no\"\nif answer == \"yes\" or \"y\":\n print(\"OK\")\nelse:\n print(\"Cancelled\")", + "options": [ + "SyntaxError", + "Cancelled", + "OK", + "Heç narsa" + ], + "answer": 2, + "explanation": "Bu (answer == \"yes\") or \"y\" deb öqiladi, böş bölmagan \"y\" satri esa doim rost. Uning örniga answer in (\"yes\", \"y\") deb yozing.", + "lesson": "logical-operators" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "print(True or False and False)", + "options": [ + "True", + "False", + "None", + "SyntaxError" + ], + "answer": 0, + "explanation": "and or dan oldin hisoblanadi, şuning uçun bu True or (False and False), yaʼni True.", + "lesson": "logical-operators" + }, + { + "question": "Qaysi şart nolga bölişdan xavfsiz saqlaydi?", + "options": [ + "total / count > 10 and count != 0", + "not count and total / count > 10", + "count != 0 or total / count > 10", + "count != 0 and total / count > 10" + ], + "answer": 3, + "explanation": "and çap tomon False bölişi bilanoq töxtaydi, şuning uçun bölişni ötkazib yuboriş uçun himoya tekşiruvi birinçi kelişi kerak.", + "lesson": "logical-operators" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "command = \"halt\"\nmatch command:\n case \"go\" | \"start\":\n print(\"Moving\")\n case \"stop\" | \"halt\":\n print(\"Stopping\")\n case _:\n print(\"Unknown command\")", + "options": [ + "Moving", + "Stopping", + "Unknown command", + "Heç narsa" + ], + "answer": 1, + "explanation": "| bitta case ga bir neça qiymatga mos keliş imkonini beradi. \"halt\" ikkinçi case ga mos keladi.", + "lesson": "match-statement" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "color = \"green\"\nmatch color:\n case \"red\":\n print(\"Töxta\")\n case other:\n print(\"Nomaʼlum:\", other)", + "options": [ + "Nomaʼlum: green", + "Hiç narsa", + "NameError", + "SyntaxError" + ], + "answer": 0, + "explanation": "case dagi yalanğoç nom - tutib oluvçi (capture) andoza: u istalgan qiymatga mos keladi va uni boğlaydi, şuning uçun oldingi case lar mos kelmasa oxirgisi doim işlaydi. Şuning uçun u eng oxirida turişi kerak.", + "lesson": "match-statement" + }, + { + "question": "Bu kodda nima notöğri?", + "code": "age = 18\nif age = 18:\n print(\"Just turned 18\")", + "options": [ + "Heç narsa, u Just turned 18 ni çop etadi", + "== örniga = işlatilgan, şuning uçun Python SyntaxError çaqiradi", + "if şarti qavs içida bölişi kerak", + "print çekiniş bilan yozilmasligi kerak" + ], + "answer": 1, + "explanation": "Bitta = qiymat beradi; taqqoslaş uçun == kerak. Python SyntaxError bilan töxtaydi va hatto tuzatişni ham taklif qiladi.", + "lesson": "if-elif-else" + } + ] +} diff --git a/docs/.vitepress/quizzes/uz/module-04.json b/docs/.vitepress/quizzes/uz/module-04.json new file mode 100644 index 0000000..a90ef52 --- /dev/null +++ b/docs/.vitepress/quizzes/uz/module-04.json @@ -0,0 +1,135 @@ +{ + "module": "04 · Sikllar", + "title": "Nazorat: Sikllar", + "intro": "while va for sikllarini kuzata olişingiz, ularni break va continue bilan boşqara olişingiz va sikllarda köp işlatiladigan usullarni qöllay olişingizni tekşiring.", + "questions": [ + { + "question": "Bu kod nimani çop etadi?", + "code": "for i in range(1, 10, 3):\n print(i, end=\" \")", + "options": [ + "1 3 5 7 9", + "1 4 7", + "0 3 6 9", + "1 4 7 10" + ], + "answer": 1, + "explanation": "range(1, 10, 3) 1 dan boşlanadi, 3 qadam bilan boradi va 10 dan oldin töxtaydi.", + "lesson": "for-loops-and-range" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "count = 1\nwhile count <= 3:\n count += 1\n print(count, end=\" \")", + "options": [ + "2 3 4", + "1 2 3", + "1 2 3 4", + "2 3" + ], + "answer": 0, + "explanation": "Yangilaş print dan oldin bajariladi, şuning uçun har bir çop etilgan qiymat allaqaçon bittaga katta. Odatda yangilaş oxirida kelişi kerak.", + "lesson": "while-loops" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "for n in range(1, 4):\n total = 0\n total += n\nprint(total)", + "options": [ + "3", + "0", + "10", + "6" + ], + "answer": 0, + "explanation": "total har bir takrorlanişda 0 ga qaytariladi, şuning uçun faqat oxirgi son qoladi. total = 0 ni sikldan oldin yarating.", + "lesson": "for-loops-and-range" + }, + { + "question": "Bu kodni işga tuşirganda nima böladi?", + "code": "for i in 5:\n print(i)", + "options": [ + "SyntaxError", + "1 dan 5 gaça çop etadi", + "TypeError", + "0 dan 4 gaça çop etadi" + ], + "answer": 2, + "explanation": "Son - aylanib çiqiş mumkin bölgan ketma-ketlik emas. Beş marta aylaniş uçun range(5) dan foydalaning.", + "lesson": "for-loops-and-range" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "for n in range(1, 6):\n if n == 3:\n continue\n if n == 5:\n break\n print(n, end=\" \")", + "options": [ + "1 2", + "1 2 3 4", + "1 2 4 5", + "1 2 4" + ], + "answer": 3, + "explanation": "continue 3 ni ötkazib yuborib davom etadi; break esa n 5 ga teng bölganda, u çop etilişidan oldin siklni töxtatadi.", + "lesson": "break-continue-else" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "for name in [\"Aziza\", \"Bekzod\"]:\n if name == \"Dilnoza\":\n print(\"Found\")\n break\nelse:\n print(\"Not found\")", + "options": [ + "Found", + "Heç narsa", + "Not found", + "Found va Not found" + ], + "answer": 2, + "explanation": "Siklning else bloki sikl break siz tugaganda bajariladi. Dilnoza topilmaydi, şuning uçun break heç qaçon sodir bölmaydi.", + "lesson": "break-continue-else" + }, + { + "question": "Bir for sikli içida boşqa for sikli bor. Içki sikldagi break nima qiladi?", + "options": [ + "Içki va taşqi siklning ikkalasini töxtatadi", + "Içki siklning bitta takrorini ötkazib yuboradi", + "Butun dasturni birdaniga töxtatadi", + "Faqat içki siklni töxtatadi" + ], + "answer": 3, + "explanation": "break faqat eng içki sikldan çiqadi. Ikkalasini töxtatiş uçun bayroq yoki return li funksiyadan foydalaning.", + "lesson": "break-continue-else" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "temps = [-5, -2, -9]\nhighest = 0\nfor t in temps:\n if t > highest:\n highest = t\nprint(highest)", + "options": [ + "-2", + "0", + "-9", + "-5" + ], + "answer": 1, + "explanation": "highest ni 0 dan boşlaş xato: heç bir manfiy son undan katta emas, şuning uçun röyxatda bölmasa ham 0 çop etiladi. Birinçi elementdan boşlang.", + "lesson": "loop-patterns" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "n = 3\nwhile n > 0:\n n -= 1\nelse:\n print(\"tayyor\", n)", + "options": [ + "tayyor 0", + "tayyor 3", + "Hiç narsa", + "SyntaxError" + ], + "answer": 0, + "explanation": "while siklining else bloki şart yolğon bölganda (break bölmasa) işlaydi. Şu paytga kelib n 0 ga yetgan.", + "lesson": "break-continue-else" + }, + { + "question": "Har bir ismni örni (1, 2, 3...) bilan çop etişingiz kerak. Eng tuşunarli usul qaysi?", + "options": [ + "for i in range(len(names)):\n print(i + 1, names[i])", + "for i, name in enumerate(names, start=1):\n print(i, name)", + "for name in names:\n print(names.index(name) + 1, name)", + "i = 0\nwhile True:\n print(i, names[i])" + ], + "answer": 1, + "explanation": "enumerate() ham örinni, ham elementni beradi, start=1 esa sanaşni 1 dan boşlaydi.", + "lesson": "loop-patterns" + } + ] +} diff --git a/docs/.vitepress/quizzes/uz/module-05.json b/docs/.vitepress/quizzes/uz/module-05.json new file mode 100644 index 0000000..e275366 --- /dev/null +++ b/docs/.vitepress/quizzes/uz/module-05.json @@ -0,0 +1,137 @@ +{ + "module": "05 · Kolleksiyalar", + "title": "Nazorat: Kolleksiyalar", + "intro": "Röyxatlar, kortejlar, luğatlar, töplamlar, içma-iç maʼlumotlar va comprehension ifodalari böyiça bilimingizni sinab köring.", + "questions": [ + { + "question": "Bu kod nimani çop etadi?", + "code": "words = [\"kiwi\", \"fig\", \"apple\"]\nprint(sorted(words, key=len))", + "options": [ + "['fig', 'kiwi', 'apple']", + "['apple', 'fig', 'kiwi']", + "['kiwi', 'fig', 'apple']", + "[3, 4, 5]" + ], + "answer": 0, + "explanation": "key=len har bir sözni uzunligi böyiça saralaydi (3, 4, 5). Kalit faqat tartibni belgilaydi; qaytariladigan narsa - sözlarning özi.", + "lesson": "list-operations-and-sorting" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "a = [1, 2, 3]\nb = a\nb.append(4)\nprint(a)", + "options": [ + "[1, 2, 3]", + "[4]", + "[1, 2, 3, 4]", + "None" + ], + "answer": 2, + "explanation": "b = a nusxa yaratmaydi; ikkala nom ham bitta röyxatga işora qiladi. Alohida röyxat oliş uçun a.copy() dan foydalaning.", + "lesson": "lists" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "scores = [3, 1, 2]\nranked = sorted(scores)\nprint(scores, ranked)", + "options": [ + "[1, 2, 3] [1, 2, 3]", + "[3, 1, 2] [1, 2, 3]", + "[3, 1, 2] None", + "None [1, 2, 3]" + ], + "answer": 1, + "explanation": "sorted() .sort() dan farqli ravişda yangi saralangan röyxat qaytaradi va aslini özgartirmaydi.", + "lesson": "list-operations-and-sorting" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "colors = (\"red\")\nprint(len(colors))", + "options": [ + "1", + "0", + "TypeError", + "3" + ], + "answer": 3, + "explanation": "Vergulsiz (\"red\") şunçaki qavs içidagi \"red\" satri, unda 3 ta belgi bor. Bir elementli kortejga vergul kerak: (\"red\",).", + "lesson": "tuples-and-unpacking" + }, + { + "question": "Bu kodni işga tuşirganda nima böladi?", + "code": "name, age = (\"Aziza\", 20, \"Tashkent\")\nprint(name, age)", + "options": [ + "Aziza 20 ni çop etadi", + "TypeError", + "ValueError", + "IndexError" + ], + "answer": 2, + "explanation": "Qiymatlar 3 ta, özgaruvçilar esa atigi 2 ta. Sonini moslang yoki ortiqçasini *rest bilan yiğing.", + "lesson": "tuples-and-unpacking" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "capitals = {\"Uzbekistan\": \"Tashkent\", \"Japan\": \"Tokyo\"}\nprint(\"Tokyo\" in capitals)", + "options": [ + "False", + "True", + "Tokyo", + "KeyError" + ], + "answer": 0, + "explanation": "in luğatning qiymatlarini emas, kalitlarini tekşiradi. Qiymatlar orasidan qidiriş uçun \"Tokyo\" in capitals.values() dan foydalaning.", + "lesson": "dictionaries" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "user = {\"name\": \"Aziza\"}\nprint(user.get(\"email\", \"unknown\"))", + "options": [ + "email", + "None", + "KeyError", + "unknown" + ], + "answer": 3, + "explanation": ".get() kalit yöq bölganda KeyError çaqiriş örniga siz bergan standart qiymatni qaytaradi.", + "lesson": "dictionaries" + }, + { + "question": "Bu kodni işga tuşirganda nima böladi?", + "code": "items = {}\nitems.add(\"x\")\nprint(items)", + "options": [ + "{'x'} ni çop etadi", + "AttributeError", + "KeyError", + "{} ni çop etadi" + ], + "answer": 1, + "explanation": "{} töplam emas, böş luğat yaratadi, luğatlarda esa add metodi yöq. Böş töplam uçun set() dan foydalaning.", + "lesson": "sets" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "grid = [[0] * 3] * 3\ngrid[0][0] = 1\nprint(grid[1])", + "options": [ + "[0, 0, 0]", + "[1, 1, 1]", + "[1, 0, 0]", + "IndexError" + ], + "answer": 2, + "explanation": "[[0] * 3] * 3 bitta içki röyxatni uç marta takrorlaydi, şuning uçun bitta qatorni özgartiriş hammasini özgartiradi. Qatorlarni comprehension bilan yarating.", + "lesson": "nested-data" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "print([n * 2 for n in range(5) if n % 2 == 0])", + "options": [ + "[0, 2, 4, 6, 8]", + "[0, 4, 8]", + "[2, 6]", + "[0, 1, 2, 3, 4]" + ], + "answer": 1, + "explanation": "if faqat 0, 2, 4 juft sonlarni qoldiradi va ularning har biri ikki barobar oşiriladi.", + "lesson": "comprehensions" + } + ] +} diff --git a/docs/.vitepress/quizzes/uz/module-06.json b/docs/.vitepress/quizzes/uz/module-06.json new file mode 100644 index 0000000..002ad88 --- /dev/null +++ b/docs/.vitepress/quizzes/uz/module-06.json @@ -0,0 +1,136 @@ +{ + "module": "06 · Funksiyalar", + "title": "Nazorat: Funksiyalar", + "intro": "Funksiyalar yaratiş, argumentlar uzatiş, qiymat qaytariş va köriniş sohasi haqida mulohaza yuritişni uddalay olişingizni tekşiring.", + "questions": [ + { + "question": "Bu kod bajarilgandan keyin result da nima saqlanadi?", + "code": "def double(n):\n print(n * 2)\n\nresult = double(5)", + "options": [ + "None", + "10", + "20", + "0" + ], + "answer": 0, + "explanation": "Funksiya 10 ni çop etadi, lekin unda return buyruği yöq, şuning uçun u None qaytaradi.", + "lesson": "return-values" + }, + { + "question": "Bu kodni işga tuşirganda nima böladi?", + "code": "def greet(name, greeting):\n print(f\"{greeting}, {name}!\")\n\ngreet(\"Aziza\")", + "options": [ + "Hello, Aziza! ni çop etadi", + "None, Aziza! ni çop etadi", + "TypeError", + "NameError" + ], + "answer": 2, + "explanation": "greet ning ikkita majburiy parametri bor, lekin faqat bitta argument uzatilgan. Ikkalasini uzating yoki greeting ga standart qiymat bering.", + "lesson": "defining-functions" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "def power(base, exp=2):\n return base ** exp\n\nprint(power(3), power(2, exp=3))", + "options": [ + "6 8", + "9 8", + "9 9", + "3 6" + ], + "answer": 1, + "explanation": "power(3) standart exp=2 dan foydalanadi, şuning uçun 3 ** 2 natijasi 9. Kalit sözli exp=3 argumenti uni almaştiradi: 2 ** 3 natijasi 8.", + "lesson": "parameters-and-arguments" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "def add_item(item, items=[]):\n items.append(item)\n return items\n\nadd_item(\"a\")\nprint(add_item(\"b\"))", + "options": [ + "['b']", + "[]", + "['a']", + "['a', 'b']" + ], + "answer": 3, + "explanation": "Standart röyxat funksiya aniqlanganda bir marta yaratiladi va çaqirişlar orasida umumiy böladi. items=None dan foydalaning va röyxatni funksiya içida yarating.", + "lesson": "parameters-and-arguments" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "def total(*prices):\n return sum(prices)\n\nprint(total(1000, 2000), total())", + "options": [ + "3000 0", + "3000 TypeError", + "TypeError", + "(1000, 2000) ()" + ], + "answer": 0, + "explanation": "*prices istalgan sondagi pozitsion argumentlarni kortejga yiğadi, şuning uçun argumentsiz total() böş kortej oladi va sum(()) 0 ga teng.", + "lesson": "parameters-and-arguments" + }, + { + "question": "Bu kodni işga tuşirganda nima böladi?", + "code": "count = 0\n\ndef increment():\n count += 1\n\nincrement()\nprint(count)", + "options": [ + "UnboundLocalError", + "0 ni çop etadi", + "1 ni çop etadi", + "SyntaxError" + ], + "answer": 0, + "explanation": "Funksiya içida count ga qiymat beriş uni lokal qiladi, şuning uçun count += 1 uni qiymat olişidan oldin öqiydi. Uning örniga qiymatni argument sifatida uzating va natijani qaytaring.", + "lesson": "scope" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "def clear(items):\n items = []\n\ndata = [1, 2, 3]\nclear(data)\nprint(data)", + "options": [ + "[]", + "UnboundLocalError", + "None", + "[1, 2, 3]" + ], + "answer": 3, + "explanation": "items = [] faqat lokal nomni yangi röyxatga yönaltiradi; çaqiruvçining röyxati özgarmaydi. items.clear() uni özgartirgan bölardi.", + "lesson": "scope" + }, + { + "question": "Bu funksiyaning qaysi varianti qayta işlatiş va test qiliş uçun eng qulay?", + "options": [ + "def total():\n price = float(input(\"Price: \"))\n print(price * 1.12)", + "def total(price, tax_rate):\n return price * (1 + tax_rate)", + "def total(price):\n print(price * 1.12)", + "def total():\n global price\n price = price * 1.12" + ], + "answer": 1, + "explanation": "U kirişlarni parametr sifatida oladi va natijani qaytaradi, uni bitta vaziyatga boğlab qöyadigan input(), print() yoki global özgaruvçilar yöq.", + "lesson": "designing-functions" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "items = [(\"non\", 5000), (\"çoy\", 3000), (\"oş\", 25000)]\ncheapest = sorted(items, key=lambda x: x[1])[0]\nprint(cheapest[0])", + "options": [ + "non", + "oş", + "çoy", + "3000" + ], + "answer": 2, + "explanation": "lambda sorted ga narxlarni taqqoslaşni aytadi, şuning uçun eng arzon element - çoy birinçi keladi.", + "lesson": "lambda-and-higher-order-functions" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "result = map(str.upper, [\"a\", \"b\"])\nprint(list(result), list(result))", + "options": [ + "['A', 'B'] ['A', 'B']", + "['A', 'B'] []", + " []", + "TypeError" + ], + "answer": 1, + "explanation": "map obyektini faqat bir marta aylanib çiqiş mumkin. Birinçi list() uni tugatadi, şuning uçun ikkinçisiga heç narsa qolmaydi.", + "lesson": "lambda-and-higher-order-functions" + } + ] +} diff --git a/docs/.vitepress/quizzes/uz/module-07.json b/docs/.vitepress/quizzes/uz/module-07.json new file mode 100644 index 0000000..fc02b3f --- /dev/null +++ b/docs/.vitepress/quizzes/uz/module-07.json @@ -0,0 +1,135 @@ +{ + "module": "07 · Modullar va standart kutubxona", + "title": "Nazorat: Modullar va standart kutubxona", + "intro": "Modullarni import qila olişingiz hamda math, random, statistics, datetime va collections dan foydalana olişingizni tekşiring.", + "questions": [ + { + "question": "Bu kodni işga tuşirganda nima böladi?", + "code": "from math import sqrt\n\nprint(math.sqrt(25))", + "options": [ + "NameError", + "5.0 ni çop etadi", + "ImportError", + "AttributeError" + ], + "answer": 0, + "explanation": "from math import sqrt faqat sqrt nomini aniqlaydi, math ni emas. sqrt(25) deb yozing yoki import math dan foydalaning.", + "lesson": "modules-and-imports" + }, + { + "question": "Bekzod zar öyinini random.py deb saqladi va random.randint birdan işlamay qoldi. Nega?", + "options": [ + "random standart kutubxonaga kirmaydi", + "Fayllarda import sözi bölişi mumkin emas", + "Python haqiqiy modul örniga avval uning özining random.py faylini topadi", + "U import random.py deb yozişi kerak" + ], + "answer": 2, + "explanation": "Python avval skriptning öz papkasidan qidiradi. Faylni dice_game.py kabi boşqa nomga özgartiring.", + "lesson": "modules-and-imports" + }, + { + "question": "if __name__ == \"__main__\": nima qiliş imkonini beradi?", + "options": [ + "Fayldagi funksiyalarni tezroq işlatiş", + "Kodni faqat fayl tögridan-tögri işga tuşirilganda bajariş", + "Boşqa moduldagi barça nomlarni import qiliş", + "Python birinçi öqişi kerak bölgan funksiyani belgilaş" + ], + "answer": 1, + "explanation": "Boşqa fayl modulingizni import qilganda __name__ modul nomiga teng böladi, şuning uçun bu tekşiruv ostidagi kod ötkazib yuboriladi.", + "lesson": "modules-and-imports" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "import math\n\nprint(math.floor(-3.7), math.ceil(-3.7))", + "options": [ + "-3 -4", + "-4 -4", + "-3 -3", + "-4 -3" + ], + "answer": 3, + "explanation": "floor manfiy sonlar uçun ham doim pastga, ceil esa doim yuqoriga yuvarlaydi.", + "lesson": "math-random-statistics" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "import random\n\nnames = [\"Aziza\", \"Bekzod\", \"Dilnoza\"]\nshuffled = random.shuffle(names)\nprint(shuffled)", + "options": [ + "['Aziza', 'Bekzod', 'Dilnoza']", + "Aralaştirilgan röyxat", + "None", + "TypeError" + ], + "answer": 2, + "explanation": "shuffle röyxatni joyida özgartiradi va None qaytaradi. Aralaştirgandan keyin names dan foydalaning yoki yangi röyxat uçun random.sample() ni işlating.", + "lesson": "math-random-statistics" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "import statistics\n\nprint(statistics.median([3, 1, 4, 10]))", + "options": [ + "3.5", + "4.5", + "4", + "3" + ], + "answer": 0, + "explanation": "median avval maʼlumotlarni saralaydi (1, 3, 4, 10) va örtadagi ikki qiymatning örtaçasini oladi. 4.5 örtaça arifmetik (mean) bölardi.", + "lesson": "math-random-statistics" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "from datetime import date, timedelta\n\nd = date(2026, 9, 15) + timedelta(days=20)\nprint(d)", + "options": [ + "2026-09-35", + "TypeError", + "2026-10-15", + "2026-10-05" + ], + "answer": 3, + "explanation": "timedelta oylar uzunligini siz uçun hisobga oladi: 15-sentabrdan 20 kun keyin 5-oktabr böladi.", + "lesson": "dates-and-times" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "from collections import Counter\n\nletters = Counter(\"banana\")\nprint(letters.most_common(1))", + "options": [ + "[('b', 1)]", + "[('a', 3)]", + "[('n', 2)]", + "{'a': 3}" + ], + "answer": 1, + "explanation": "Counter har bir harfni sanaydi, most_common(1) esa eng köp uçraydigan bitta (element, soni) juftligi bor röyxatni qaytaradi.", + "lesson": "collections-and-itertools" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "from collections import defaultdict\n\ntotals = defaultdict(int)\nprint(totals[\"Nukus\"], len(totals))", + "options": [ + "0 1", + "KeyError", + "0 0", + "None 1" + ], + "answer": 0, + "explanation": "defaultdict dan yöq kalitni öqiş uni standart qiymat bilan qöşib qöyadi, şuning uçun qidiruv 0 qaytaradi va luğatda endi bitta yozuv bor. Qöşmasdan tekşiriş uçun 'Nukus' in totals yoki totals.get('Nukus', 0) işlating.", + "lesson": "collections-and-itertools" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "from datetime import datetime\n\nd = datetime(2026, 9, 15, 14, 30)\nprint(d.strftime(\"%d.%M.%Y\"))", + "options": [ + "15.09.2026", + "15.30.2026", + "15.9.2026", + "ValueError" + ], + "answer": 1, + "explanation": "%M - daqiqalar; oy esa %m (kiçik harf). Notögri kod xato bermaydi, şunçaki notögri maydonni formatlaydi.", + "lesson": "dates-and-times" + } + ] +} diff --git a/docs/.vitepress/quizzes/uz/module-08.json b/docs/.vitepress/quizzes/uz/module-08.json new file mode 100644 index 0000000..6f32140 --- /dev/null +++ b/docs/.vitepress/quizzes/uz/module-08.json @@ -0,0 +1,136 @@ +{ + "module": "08 · Xatolar va fayllar", + "title": "Nazorat: Xatolar va fayllar", + "intro": "Istisnolarni uşlay olişingiz, kiritilgan maʼlumotni tekşira olişingiz hamda matn, CSV va JSON fayllarni xavfsiz öqib-yoza olişingizni tekşiring.", + "questions": [ + { + "question": "Bu kod qaysi qatorlarni qanday tartibda çop etadi?", + "code": "def check(text):\n try:\n n = int(text)\n except ValueError:\n print(\"rejected\")\n else:\n print(\"accepted\")\n finally:\n print(\"done\")\n\ncheck(\"12\")", + "options": [ + "accepted, keyin done", + "accepted", + "rejected, keyin done", + "done, keyin accepted" + ], + "answer": 0, + "explanation": "try bloki muvaffaqiyatli bajariladi, şuning uçun else işlaydi; finally esa undan keyin doim bajariladi.", + "lesson": "exceptions" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "try:\n result = 10 / 0\nexcept Exception:\n print(\"Something went wrong\")\nexcept ZeroDivisionError:\n print(\"Cannot divide by zero\")", + "options": [ + "Cannot divide by zero", + "Something went wrong", + "Ikkala xabarni", + "Heç narsa, dastur xato bilan töxtaydi" + ], + "answer": 1, + "explanation": "ZeroDivisionError Exception ning vorisi, şuning uçun birinçi mos kelgan except ğolib böladi. Aniqroq istisnolarni birinçi qöying.", + "lesson": "exceptions" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "class OutOfStockError(Exception):\n pass\n\ndef buy(stock):\n if stock == 0:\n raise OutOfStockError(\"no tea left\")\n return stock - 1\n\ntry:\n buy(0)\nexcept OutOfStockError as e:\n print(f\"Error: {e}\")", + "options": [ + "Error: OutOfStockError", + "Heç narsa, dastur xato bilan töxtaydi", + "Error: no tea left", + "TypeError" + ], + "answer": 2, + "explanation": "Maxsus klass Exception dan meros oladi, şuning uçun u xabar saqlay oladi, str(e) esa şu xabarni beradi.", + "lesson": "raising-and-custom-exceptions" + }, + { + "question": "Quyidagi matnni (satrni) qaysi çaqiruv Python luğatiga aylantiradi?", + "code": "text = '{\"city\": \"Nukus\", \"temp\": 28}'", + "options": [ + "json.loads(text)", + "json.load(text)", + "json.dumps(text)", + "json.dump(text)" + ], + "answer": 0, + "explanation": "loads satrdan öqiydi (s - string); load oçiq fayldan öqiydi. dumps va dump teskari yönalişda, Python dan JSON ga işlaydi.", + "lesson": "json" + }, + { + "question": "Foydalanuvçi \" Yes\" (boşida böşliq bilan) deb yozdi. Bu kod nimani çop etadi?", + "code": "answer = \" Yes\"\nif answer == \"yes\":\n print(\"Confirmed\")\nelse:\n print(\"Not confirmed\")", + "options": [ + "Tasdiqlandi", + "Tasdiqlanmadi", + "ValueError", + "Hiç narsa" + ], + "answer": 1, + "explanation": "\" Yes\" \"yes\" ga teng emas: böşliq ham, bosh harf ham ahamiyatli. Avval answer.strip().lower() bilan normallaştiring, keyin taqqoslang.", + "lesson": "input-validation" + }, + { + "question": "Nega \"-3\".isdigit() harorat yaroqli son ekanini tekşirişning yomon usuli?", + "options": [ + "Manfiy sonlar uçun ValueError çaqiradi", + "Har qanday böş bölmagan satr uçun True qaytaradi", + "False qaytaradi, şuning uçun tögri manfiy sonlar rad etiladi", + "Faqat 3.5 kabi float satrlar uçun işlaydi" + ], + "answer": 2, + "explanation": "Minus belgisi raqam emas, şuning uçun isdigit() False qaytaradi. Uning örniga try içida int() yoki float() bilan özgartiring.", + "lesson": "input-validation" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "with open(\"log.txt\", \"w\", encoding=\"utf-8\") as f:\n f.write(\"first\\n\")\nwith open(\"log.txt\", \"w\", encoding=\"utf-8\") as f:\n f.write(\"second\\n\")\nwith open(\"log.txt\", encoding=\"utf-8\") as f:\n print(f.read(), end=\"\")", + "options": [ + "first va second (ikki qator)", + "first", + "Heç narsa", + "second" + ], + "answer": 3, + "explanation": "\"w\" rejimi fayl har safar oçilganda uni tozalab yuboradi. Oxiriga qöşiş uçun \"a\" dan foydalaning.", + "lesson": "files-and-pathlib" + }, + { + "question": "Bu kod işga tuşganda nima böladi?", + "code": "import csv, io\nrows = csv.DictReader(io.StringIO(\"name,score\\nAziza,92\\nBekzod,78\\n\"))\ntotal = sum(row[\"score\"] for row in rows)\nprint(total)", + "options": [ + "170 ni çop etadi", + "TypeError", + "ValueError", + "9278 ni çop etadi" + ], + "answer": 1, + "explanation": "CSV dagi har bir qiymat satr, şuning uçun sum() int va str ni qöşişga urinadi. int(row[\"score\"]) bilan özgartiring.", + "lesson": "csv" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "import json\nmedals = {1: \"gold\", 2: \"silver\"}\ndata = json.loads(json.dumps(medals))\nprint(data)", + "options": [ + "{'1': 'gold', '2': 'silver'}", + "{1: 'gold', 2: 'silver'}", + "[1, 2]", + "TypeError" + ], + "answer": 0, + "explanation": "JSON obyekt kalitlari doim satr böladi, şuning uçun son kalitlar JSON ga aylantirib qaytarilgandan keyin satr bölib qaytadi.", + "lesson": "json" + }, + { + "question": "Oxirgi qatorda nima böladi?", + "code": "with open(\"notes.txt\", \"w\", encoding=\"utf-8\") as file:\n file.write(\"first line\\n\")\nfile.write(\"second line\\n\")", + "options": [ + "Matn notes.txt oxiriga qöşiladi", + "Fayl avtomatik qayta oçiladi", + "ValueError", + "NameError" + ], + "answer": 2, + "explanation": "with bloki tugaganda faylni yopadi, yopiq faylga yoziş esa ValueError: I/O operation on closed file xatosini çaqiradi.", + "lesson": "context-managers-basics" + } + ] +} diff --git a/docs/.vitepress/quizzes/uz/module-09.json b/docs/.vitepress/quizzes/uz/module-09.json new file mode 100644 index 0000000..2023b81 --- /dev/null +++ b/docs/.vitepress/quizzes/uz/module-09.json @@ -0,0 +1,136 @@ +{ + "module": "09 · Klasslar va obyektlar", + "title": "Nazorat: Klasslar va obyektlar", + "intro": "Klasslar yarata olişingiz, nusxa va klass atributlari bilan işlay olişingiz, xossalardan foydalana olişingiz va maxsus metodlar yoza olişingizni tekşiring.", + "questions": [ + { + "question": "Bu kod nimani çop etadi?", + "code": "class Temperature:\n def __init__(self, celsius):\n self.celsius = celsius\n\n @classmethod\n def from_fahrenheit(cls, f):\n return cls((f - 32) * 5 / 9)\n\nt = Temperature.from_fahrenheit(212)\nprint(t.celsius)", + "options": [ + "100.0", + "212", + "TypeError", + "100" + ], + "answer": 0, + "explanation": "classmethod klassni cls sifatida oladi, şuning uçun cls(...) yangi Temperature yaratadi. (212 - 32) * 5 / 9 bu 100.0 - / tufayli float.", + "lesson": "class-attributes-and-methods" + }, + { + "question": "Bu kod işga tuşganda nima böladi?", + "code": "class Book:\n def __init__(self, title):\n title = title\n\nbook = Book(\"Python Basics\")\nprint(book.title)", + "options": [ + "Python Basics ni çop etadi", + "None ni çop etadi", + "TypeError", + "AttributeError" + ], + "answer": 3, + "explanation": "self. siz title faqat __init__ içidagi lokal özgaruvçi, şuning uçun obyekt heç qaçon title atributiga ega bölmaydi.", + "lesson": "classes-and-objects" + }, + { + "question": "Oxirgi qatorda nima böladi?", + "code": "class Todo:\n def __init__(self):\n self.tasks = []\n\n def add(self, task):\n self.tasks.append(task)\n\ntodo = Todo().add(\"buy bread\")\nprint(todo.tasks)", + "options": [ + "['buy bread'] ni çop etadi", + "AttributeError", + "TypeError", + "None ni çop etadi" + ], + "answer": 1, + "explanation": "add() None qaytaradi, şuning uçun todo None ga teng. Avval obyektni yarating, keyin add() ni alohida qatorda çaqiring.", + "lesson": "methods-and-attributes" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "class Wallet:\n def __init__(self):\n self.cash = 1000\n def spend(self, amount):\n self.cash -= amount\n if self.cash < 0:\n raise ValueError(\"Not enough cash\")\nw = Wallet()\ntry:\n w.spend(5000)\nexcept ValueError:\n print(w.cash)", + "options": [ + "1000", + "-4000", + "ValueError", + "0" + ], + "answer": 1, + "explanation": "Holat tekşirişdan oldin özgaradi: avval self.cash kamayadi, istisno keyin çaqiriladi (va tutiladi), şuning uçun hamyon -4000 da qoladi. Avval tekşiring, keyin holatni özgartiring.", + "lesson": "methods-and-attributes" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "class Student:\n count = 0\n\n def __init__(self, name):\n self.name = name\n self.count += 1\n\na = Student(\"Aziza\")\nb = Student(\"Bekzod\")\nprint(Student.count, a.count)", + "options": [ + "2 1", + "2 2", + "0 1", + "AttributeError" + ], + "answer": 2, + "explanation": "self.count += 1 har bir obyektda nusxa atributini yaratadi va Student.count ni 0 da qoldiradi. Student.count += 1 dan foydalaning.", + "lesson": "class-attributes-and-methods" + }, + { + "question": "Bu kod işga tuşganda nima böladi?", + "code": "class Rectangle:\n def __init__(self, width, height):\n self.width = width\n self.height = height\n\n @property\n def area(self):\n return self.width * self.height\n\nprint(Rectangle(4, 5).area())", + "options": [ + "20 ni çop etadi", + "Metod obyektini çop etadi", + "AttributeError", + "TypeError" + ], + "answer": 3, + "explanation": "Xossa qavssiz öqiladi: Rectangle(4, 5).area allaqaçon 20 soni, sonni esa çaqirib bölmaydi.", + "lesson": "properties-and-encapsulation" + }, + { + "question": "Product klassida price nomli property bor. Klass içida qiymatning özi qayerda saqlanişi kerak?", + "options": [ + "self.price", + "self._price", + "Product.price", + "Global özgaruvçida" + ], + "answer": 1, + "explanation": "Xossa içida self.price ga qiymat beriş setterni qayta-qayta çaqiradi va RecursionError ga olib keladi. Maʼlumotni self._price kabi boşqa nom ostida saqlang.", + "lesson": "properties-and-encapsulation" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "class Product:\n def __init__(self, name):\n self.name = name\n\n def __repr__(self):\n return f\"Product({self.name!r})\"\n\n def __str__(self):\n return self.name\n\nitems = [Product(\"Tea\")]\nprint(items[0], items)", + "options": [ + "Tea [Product('Tea')]", + "Tea [Tea]", + "Product('Tea') [Product('Tea')]", + "Tea ['Tea']" + ], + "answer": 0, + "explanation": "print() obyektning özi uçun __str__ dan foydalanadi, röyxat esa öz elementlarini __repr__ bilan körsatadi.", + "lesson": "special-methods" + }, + { + "question": "Bu kod nima qiladi?", + "code": "class Product:\n def __init__(self, name, price):\n self.name = name\n self.price = price\n\n def __eq__(self, other):\n return self.name == other.name\n\nprint(Product(\"Tea\", 15000) == Product(\"Tea\", 12000))\nprint({Product(\"Tea\", 15000)})", + "options": [ + "True ni çop etadi, keyin bitta mahsulotli töplamni", + "False ni çop etadi, keyin TypeError çaqiradi", + "True ni çop etadi, keyin TypeError çaqiradi", + "True ni çop etadi, keyin ikkita mahsulotli töplamni" + ], + "answer": 2, + "explanation": "Nomlar mos keladi, şuning uçun == True. __eq__ ni aniqlaş __hash__ ni None qiladi, şuning uçun obyektni töplamga qöşib bölmaydi.", + "lesson": "special-methods" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "class Cart:\n def __init__(self, items):\n self.items = items\n\n def __len__(self):\n return len(self.items)\n\ncart = Cart([\"tea\", \"non\"])\nprint(len(cart), bool(Cart([])))", + "options": [ + "2 False", + "2 True", + "TypeError", + "AttributeError" + ], + "answer": 0, + "explanation": "len(cart) __len__ ni çaqiradi. __bool__ bölmasa rostlik tekşiruvi __len__ ga tayanadi, şuning uçun böş savat False.", + "lesson": "operators-and-containers" + } + ] +} diff --git a/docs/.vitepress/quizzes/uz/module-10.json b/docs/.vitepress/quizzes/uz/module-10.json new file mode 100644 index 0000000..7797a7b --- /dev/null +++ b/docs/.vitepress/quizzes/uz/module-10.json @@ -0,0 +1,135 @@ +{ + "module": "10 · Obyektga yönaltirilgan loyihalaş", + "title": "Nazorat: Obyektga yönaltirilgan loyihalaş", + "intro": "Vorislik va kompozitsiya orasida tanlay olişingiz, ABC, dataclass va enum lardan foydalana olişingiz hamda type hintlarni töğri öqiy olişingizni tekşiring.", + "questions": [ + { + "question": "Oxirgi qatorda nima böladi?", + "code": "class Employee:\n def __init__(self, name):\n self.name = name\n\nclass Manager(Employee):\n def __init__(self, name, team_size):\n self.team_size = team_size\n\nboss = Manager(\"Dilnoza\", 5)\nprint(boss.name)", + "options": [ + "Dilnoza ni çop etadi", + "None ni çop etadi", + "AttributeError", + "TypeError" + ], + "answer": 2, + "explanation": "Voris klassda __init__ ni aniqlaş ota klassnikini almaştiradi, şuning uçun self.name heç qaçon belgilanmaydi. Avval super().__init__(name) ni çaqiring.", + "lesson": "inheritance" + }, + { + "question": "Qaysi maslahat (hint) scores butun sonlar röyxati yoki None ekanini bildiradi?", + "options": [ + "scores: list[int] | None", + "scores: List[int, None]", + "scores: list | None[int]", + "scores: Optional(list[int])" + ], + "answer": 0, + "explanation": "Zamonaviy Python da list[int] - ornatilgan umumiy tur, X | None esa 'X yoki None' degani. typing dagi Optional[X] ayni narsaning eskiroq yozilişi.", + "lesson": "type-hints" + }, + { + "question": "Bu kod işga tuşganda nima böladi?", + "code": "from abc import ABC, abstractmethod\nclass Shape(ABC):\n @abstractmethod\n def area(self): ...\nclass Square(Shape):\n def __init__(self, side):\n self.side = side\n def Area(self):\n return self.side ** 2\nprint(Square(3).Area())", + "options": [ + "9 ni çop etadi", + "None ni çop etadi", + "TypeError", + "AttributeError" + ], + "answer": 2, + "explanation": "Katta A harfli Area - boşqa nom, şuning uçun area hamon abstrakt va ABC Square yaratişni rad etadi.", + "lesson": "polymorphism-and-abcs" + }, + { + "question": "Order klassi Logger klassi yordamida log xabarlarini yozişi kerak. Qaysi yeçim eng yaxşi?", + "options": [ + "class Order(Logger): undan vorislik oliş", + "Order ga logger atributi beriş", + "log metodini Order ga nusxalaş", + "class Logger(Order): Logger ni farzand qiliş" + ], + "answer": 1, + "explanation": "Buyurtma logger emas, şuning uçun u \"is-a\" (... hisoblanadi) sinovidan ötmaydi. Buyurtmada logger bor - bu kompozitsiya.", + "lesson": "composition" + }, + { + "question": "Oxirgi qatorda nima bölady?", + "code": "from dataclasses import dataclass, field\n\n@dataclass(frozen=True)\nclass Point:\n x: int\n tags: list = field(default_factory=list)\n\np = Point(1)\np.x = 5", + "options": [ + "p.x ga 5 ni yozadi", + "FrozenInstanceError", + "TypeError", + "Yangi Point yaratadi" + ], + "answer": 1, + "explanation": "frozen=True dataklassni özgarmas qiladi: maydonga qiymat beriş dataclasses.FrozenInstanceError çaqiradi. field(default_factory=list) har bir nusxaga öz röyxatini beradi.", + "lesson": "dataclasses" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "from dataclasses import dataclass\n\n@dataclass\nclass Book:\n title: str\n pages = 100\n\nprint(Book(\"Days Gone By\"))", + "options": [ + "Book(title='Days Gone By', pages=100)", + "TypeError", + "Book(title='Days Gone By')", + "Book('Days Gone By')" + ], + "answer": 2, + "explanation": "Annotatsiyasiz pages faqat klass atributi, maydon emas, şuning uçun u __init__ va repr da yöq.", + "lesson": "dataclasses" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "from dataclasses import dataclass, field\n\n@dataclass(order=True)\nclass Score:\n points: int\n name: str = field(compare=False)\n\nscores = [Score(90, \"Aziza\"), Score(75, \"Bekzod\"), Score(90, \"Anvar\")]\nprint(max(scores).name, Score(90, \"X\") == Score(90, \"Y\"))", + "options": [ + "Aziza True", + "Anvar True", + "Aziza False", + "TypeError" + ], + "answer": 0, + "explanation": "compare=False bilan faqat points taqqoslanadi. Ikki natija 90 da teng, max() esa birinçi topganini qaytaradi.", + "lesson": "dataclasses" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "from enum import Enum\n\nclass Status(Enum):\n PAID = \"paid\"\n\nstatus = Status(\"paid\")\nprint(status == \"paid\", status is Status.PAID)", + "options": [ + "True True", + "True False", + "False False", + "False True" + ], + "answer": 3, + "explanation": "Oddiy Enum aʼzosi heç qaçon öz xom qiymatiga teng bölmaydi. Status(\"paid\") aʼzoni qidirib topadi, şuning uçun is tekşiruvi True.", + "lesson": "enums" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "from enum import Enum\n\nclass Size(Enum):\n SMALL = \"S\"\n LARGE = \"L\"\n\nprint(Size[\"SMALL\"].value, Size(\"L\").name)", + "options": [ + "SMALL L", + "S LARGE", + "S L", + "ValueError" + ], + "answer": 1, + "explanation": "Kvadrat qavslar nom böyiça, oddiy qavslar esa qiymat böyiça qidiradi. .value \"S\" ni, .name esa \"LARGE\" ni beradi.", + "lesson": "enums" + }, + { + "question": "Type hint da list[int] deyilgan, lekin kortej uzatilgan. Nima böladi?", + "code": "def average(scores: list[int]) -> float:\n return sum(scores) / len(scores)\n\nprint(average((80, 90)))", + "options": [ + "TypeError", + "85 ni çop etadi", + "Tur tekşiruvçisi xatosi dasturni töxtatadi", + "85.0 ni çop etadi" + ], + "answer": 3, + "explanation": "Type hintlar dastur bajarilayotganda tekşirilmaydi, şuning uçun kortej muammosiz işlaydi. Faqat alohida tur tekşiruvçisi eʼtiroz bildirardi.", + "lesson": "type-hints" + } + ] +} diff --git a/docs/.vitepress/quizzes/uz/module-11.json b/docs/.vitepress/quizzes/uz/module-11.json new file mode 100644 index 0000000..11580f1 --- /dev/null +++ b/docs/.vitepress/quizzes/uz/module-11.json @@ -0,0 +1,132 @@ +{ + "module": "11 · Testlaş va xatolarni tuzatiş", + "title": "Nazorat: Testlaş va xatolarni tuzatiş", + "intro": "Foydali testlar yoza olişingiz, yaxşi test holatlarini tanlay olişingiz, pytest dan foydalana olişingiz hamda print, traceback va logging bilan xatolarni tuzata olişingizni tekşiring.", + "questions": [ + { + "question": "Bu kod işga tuşganda nima böladi?", + "code": "price = 15000\nassert(price == 20000, \"wrong price\")\nprint(\"passed?\")", + "options": [ + "AssertionError: wrong price", + "passed? ni çop etadi (SyntaxWarning bilan)", + "SyntaxError", + "Heç narsa çop etilmaydi" + ], + "answer": 1, + "explanation": "Qavslar böş bölmagan kortej yaratadi, u esa doim rost, şuning uçun assert heç qaçon xato bermaydi. assert price == 20000, \"wrong price\" deb yozing.", + "lesson": "testing-with-assert" + }, + { + "question": "0.1 + 0.2 uçun qaysi assert ötadi?", + "options": [ + "assert 0.1 + 0.2 == pytest.approx(0.3)", + "assert 0.1 + 0.2 == 0.3", + "assert round(0.1 + 0.2) == 0.3", + "assert 0.1 + 0.2 is 0.3" + ], + "answer": 0, + "explanation": "0.1 + 0.2 bu 0.30000000000000004, şuning uçun == 0.3 ötmaydi. pytest.approx (yoki math.isclose) ruxsat etilgan farq bilan taqqoslaydi.", + "lesson": "pytest-basics" + }, + { + "question": "Bu False ni çop etadi. Örtaça qiymatni test qilişning eng yaxşi usuli qaysi?", + "code": "average = (0.1 + 0.2 + 0.3) / 3\nprint(average == 0.2)", + "options": [ + "assert math.isclose(average, 0.2)", + "assert average == 0.20000000000000004", + "assert int(average) == 0", + "assert str(average) == \"0.2\"" + ], + "answer": 0, + "explanation": "Önlik sonlarda kiçik yuvarlaş xatolari bor, şuning uçun ularni math.isclose() (yoki pytest da pytest.approx) bilan taqqoslang.", + "lesson": "testing-with-assert" + }, + { + "question": "Röyxatdan ötiş formasi manfiy yoşlarni rad etişi kerak. Qaysi biri töğri?", + "options": [ + "Forma işlovçisida assert age >= 0", + "age 0 dan kiçik bölganda print(\"yomon\")", + "age 0 dan kiçik bölganda ValueError çaqiriş", + "assert age >= 0 ni try/except: pass ga öraş" + ], + "answer": 2, + "explanation": "Python -O bilan işga tuşirilganda assert buyruqlari olib taşlanadi, şuning uçun haqiqiy tekşiruvga if va raise kerak.", + "lesson": "testing-with-assert" + }, + { + "question": "Funksiya 100000 söm va undan köp buyurtmalarga çegirma beradi. Qaysi test qiymatlari töplami eng yaxşi?", + "options": [ + "50000, 60000, 70000", + "99999, 100000, 100001", + "Faqat 100000", + "200000, 300000" + ], + "answer": 1, + "explanation": "Xatolar çegaralarda yaşirinadi. Çegaradan sal pastda, aynan çegarada va sal yuqorida test qiliş >= örniga > yozilganiga öxşaş xatolarni uşlaydi.", + "lesson": "choosing-test-cases" + }, + { + "question": "tax(price) = price * 12 // 100 uçun qaysi test yaxşiroq?", + "options": [ + "assert tax(15000) == 15000 * 12 // 100", + "assert tax(15000) > 0", + "assert tax(15000) is not None", + "assert tax(15000) == 1800" + ], + "answer": 3, + "explanation": "Koddan nusxalangan kutilgan qiymat undagi xatolarni takrorlaydi. Qöl bilan hisoblab çiqilgan oddiy sondan foydalaning.", + "lesson": "choosing-test-cases" + }, + { + "question": "Siz def check_total() bor totals.py fayli joylaşgan papkada pytest ni işga tuşirasiz. pytest \"collected 0 items\" deydi. Nega?", + "options": [ + "Bu loyihada pytest örnatilmagan", + "Test fayllari va funksiyalari test_* deb nomlanişi kerak", + "Funksiya içidagi assert notögri", + "Testlar TestCase klassi içida bölişi kerak" + ], + "answer": 1, + "explanation": "pytest faqat nomi test bilan boşlanadigan fayl va funksiyalarni yiğadi. \"no tests ran\" muvaffaqiyat degani emas.", + "lesson": "pytest-basics" + }, + { + "question": "pytest bu testni işga tuşiradi. Natija qanday?", + "code": "import pytest\ndef withdraw(balance, amount):\n if amount > balance:\n raise ValueError(\"not enough\")\n return balance - amount\ndef test_too_much():\n balance = 100\n with pytest.raises(ValueError):\n balance = withdraw(balance, 500)\n assert balance == 999\n", + "options": [ + "Test ötadi, lekin assert heç qaçon tekşirilmaydi", + "balance 999 bölmagani uçun test ötmaydi", + "Test ValueError bilan ötmaydi", + "pytest testda xato (error) borligini bildiradi" + ], + "answer": 0, + "explanation": "withdraw() with bloki içida istisno çaqiradi, şuning uçun keyingi qator heç qaçon bajarilmaydi. Tekşiruvlarni with blokidan keyin qöying.", + "lesson": "pytest-basics" + }, + { + "question": "Bu skript işga tuşganda ekranda nima paydo böladi?", + "code": "import logging\nlogging.info(\"order created\")\nlogging.warning(\"stock low\")", + "options": [ + "INFO:root:order created", + "Ikkala xabar", + "Heç narsa", + "WARNING:root:stock low" + ], + "answer": 3, + "explanation": "basicConfig bölmasa daraja WARNING böladi, şuning uçun info() xabarlari taşlab yuboriladi.", + "lesson": "debugging-and-logging" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "x = 7\nitems = [\"tea\", \"bread\"]\nprint(f\"{x=} {len(items)=}\")", + "options": [ + "7 2", + "x=7 len(items)=2", + "{x=} {len(items)=}", + "x = 7, len(items) = 2" + ], + "answer": 1, + "explanation": "f-satr maydonidagi = ifoda matnini va undan keyin uning qiymatini çop etadi, bu print yordamida xatolarni tuzatişda qulay.", + "lesson": "debugging-and-logging" + } + ] +} diff --git a/docs/.vitepress/quizzes/uz/module-12.json b/docs/.vitepress/quizzes/uz/module-12.json new file mode 100644 index 0000000..9601f25 --- /dev/null +++ b/docs/.vitepress/quizzes/uz/module-12.json @@ -0,0 +1,136 @@ +{ + "module": "12 · Keyingi qadamlar", + "title": "Nazorat: Keyingi qadamlar", + "intro": "Iteratorlar, generatorlar va regulyar ifodalarni hamda matnni qayta işlaydigan dasturni qanday tuziş kerakligini tuşunişingizni tekşiring.", + "questions": [ + { + "question": "Ikkala print nimani körsatadi?", + "code": "evens = (n for n in range(10) if n % 2 == 0)\nprint(sum(evens))\nprint(sum(evens))", + "options": [ + "20, keyin 20", + "20, keyin 0", + "20, keyin xato", + "0, keyin 20" + ], + "answer": 1, + "explanation": "Birinçi sum() generatorni tugatadi, şuning uçun ikkinçisi heç qanday qiymat körmaydi va 0 qaytaradi.", + "lesson": "iterators-and-generators" + }, + { + "question": "Qaysi qatorlar qanday tartibda çop etiladi?", + "code": "def countdown(n):\n print(\"start\")\n while n > 0:\n yield n\n n -= 1\n\ngen = countdown(3)\nprint(\"created\")\nprint(next(gen), next(gen))", + "options": [ + "start, created, 3 2", + "created, 3 2", + "created, start, 3 2", + "start, 3 2, created" + ], + "answer": 2, + "explanation": "Generator funksiyasini çaqiriş faqat generator yaratadi. Tana birinçi next() da işlay boşlaydi.", + "lesson": "iterators-and-generators" + }, + { + "question": "Bu kod işga tuşganda nima böladi?", + "code": "cities = [\"Tashkent\", \"Bukhara\"]\nprint(next(cities))", + "options": [ + "Tashkent ni çop etadi", + "StopIteration", + "['Tashkent', 'Bukhara'] ni çop etadi", + "TypeError" + ], + "answer": 3, + "explanation": "Röyxat iteratsiya qilinadigan (iterable), lekin iterator emas. next(iter(cities)) dan foydalaning.", + "lesson": "iterators-and-generators" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "def chunks():\n yield from [1, 2]\n yield 3\n\nprint(list(chunks()), sum(chunks()))", + "options": [ + "[1, 2, 3] 6", + "[[1, 2], 3] 6", + "[1, 2, 3] 0", + "TypeError" + ], + "answer": 0, + "explanation": "yield from röyxatning har bir elementini birma-bir beradi. chunks() ning har bir çaqiriluvi yangi generator yaratadi, şuning uçun sum() barça qiymatlarni köradi.", + "lesson": "iterators-and-generators" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "import re\ntext = \"Total: 45000 som\"\nprint(re.match(r\"\\d+\", text))", + "options": [ + "45000", + "None", + "", + "[]" + ], + "answer": 1, + "explanation": "re.match faqat satr boşini tekşiradi, u yerda esa raqam yöq. Istalgan joydan qidiriş uçun re.search dan foydalaning.", + "lesson": "regular-expressions" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "import re\nhtml = \"Plov and Somsa\"\nprint(re.findall(r\"(.*)\", html))", + "options": [ + "['Plov', 'Somsa']", + "['Plov', 'Somsa']", + "['Plov and Somsa']", + "[]" + ], + "answer": 2, + "explanation": "Greedy .* oxirgi gaça imkon qadar köp narsani oladi. Birinçisida töxtaş uçun .*? yoki [^<]* dan foydalaning.", + "lesson": "regular-expressions" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "import re\nprint(bool(re.match(r\"\\d+\", \"123abc\")), bool(re.fullmatch(r\"\\d+\", \"123abc\")))", + "options": [ + "True False", + "True True", + "False False", + "False True" + ], + "answer": 0, + "explanation": "match muvaffaqiyatli, çunki satr raqamlar bilan boşlanadi, lekin fullmatch butun satr mos kelişini talab qiladi. Tekşiruv uçun fullmatch dan foydalaning.", + "lesson": "regular-expressions" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "import re\nm = re.search(r\"(?P\\d{2})\\.(?P\\d{2})\", \"Date: 15.09.2026\")\nprint(m.group(\"month\"), m.group(0))", + "options": [ + "15 09", + "09 15", + "09 15.09", + "15.09 09" + ], + "answer": 2, + "explanation": "Nomlangan guruhlar nomi böyiça öqiladi, group(0) esa butun moslik.", + "lesson": "regular-expressions" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "from collections import Counter\ntext = \"Plov, plov and more plov!\"\nprint(Counter(text.lower().split())[\"plov\"])", + "options": [ + "3", + "0", + "KeyError", + "1" + ], + "answer": 3, + "explanation": "split() tiniş belgilarini sözga yopişgan holda qoldiradi, şuning uçun \"plov,\" va \"plov!\" har xil söz sifatida sanaladi. Sözlarni [a-z]+ kabi regex bilan ajratib oling.", + "lesson": "text-processing-project" + }, + { + "question": "Matn tahlilçisida count_sentences(text) kabi funksiyalar maʼlumotni qayerdan olişi va çop etiş qayerda bölişi kerak?", + "options": [ + "Matnni argument sifatida oliş va qiymat qaytariş", + "Har bir funksiya içida faylni öqib çop etiş", + "Matn va natijalarni global özgaruvçilarda saqlaş", + "Hammasini bitta main() funksiyasiga joylaş" + ], + "answer": 0, + "explanation": "Argument olib, qiymat qaytaradigan sof funksiyalarni test qiliş va qayta işlatiş oson. Faylni öqiş va çop etişni çetlarda saqlang.", + "lesson": "text-processing-project" + } + ] +} diff --git a/docs/.vitepress/quizzes/uz/module-13.json b/docs/.vitepress/quizzes/uz/module-13.json new file mode 100644 index 0000000..a7f95f0 --- /dev/null +++ b/docs/.vitepress/quizzes/uz/module-13.json @@ -0,0 +1,136 @@ +{ + "module": "13 · Maʼlumotlar bilan işlaş (ixtiyoriy)", + "title": "Nazorat: Maʼlumotlar bilan işlaş (ixtiyoriy)", + "intro": "pandas bilan jadvallarni yuklay va filtrlay olişingiz, ularni umumlaştira olişingiz va matplotlib bilan tuşunarli grafiklar çiza olişingizni tekşiring.", + "questions": [ + { + "question": "Bu kod nimani çop etadi?", + "code": "import pandas as pd\ndf = pd.DataFrame({\"city\": [\"Tashkent\", \"Bukhara\", \"Samarkand\"],\n \"temp\": [31.5, 28.1, 33.0]})\nprint(df.iloc[1][\"city\"], df.loc[2, \"temp\"])", + "options": [ + "Tashkent 33.0", + "Bukhara 28.1", + "Bukhara 33.0", + "KeyError" + ], + "answer": 2, + "explanation": ".iloc örin böyiça tanlaydi (1-qator - Bukhara), .loc esa yorliq böyiça tanlaydi (2-indeks - Samarkand qatori).", + "lesson": "reading-data" + }, + { + "question": "Bu kod işga tuşganda nima böladi?", + "code": "import pandas as pd\ndf = pd.DataFrame({\"city\": [\"Tashkent\", \"Bukhara\"], \"temp\": [31.5, 28.1]})\nprint(df[\"city\", \"temp\"])", + "options": [ + "KeyError", + "Ikkala ustunni çop etadi", + "Faqat city ustunini çop etadi", + "ValueError" + ], + "answer": 0, + "explanation": "Bitta kvadrat qavs (\"city\", \"temp\") korteji bilan nomlangan bitta ustunni qidiradi. Röyxat uzating: df[[\"city\", \"temp\"]].", + "lesson": "reading-data" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "import pandas as pd\n\norders = pd.DataFrame({\"product\": [\"Tea\", \"Halva\"], \"qty\": [2, 1]})\nprices = pd.DataFrame({\"product\": [\"Tea\"], \"price\": [15000]})\nprint(len(orders.merge(prices, on=\"product\")), len(orders.merge(prices, on=\"product\", how=\"left\")))", + "options": [ + "1 2", + "2 2", + "2 1", + "KeyError" + ], + "answer": 0, + "explanation": "Içki (inner) merge faqat ikkala jadvalda bor mahsulotlarni (Tea) saqlaydi. Çap (left) merge har bir buyurtmani saqlaydi va yetişmagan narxni NaN bilan töldiradi.", + "lesson": "pandas-basics" + }, + { + "question": "Bu kod işga tuşganda nima böladi?", + "code": "import pandas as pd\ndf = pd.DataFrame({\"temp\": [31.5, 28.1], \"humidity\": [22, 30]})\nprint(df[df[\"temp\"] > 30 and df[\"humidity\"] < 25])", + "options": [ + "Tashkent qatorini çop etadi", + "ValueError", + "Böş DataFrame ni çop etadi", + "KeyError" + ], + "answer": 1, + "explanation": "and ga bitta True yoki False kerak, lekin har bir taqqoslaş butun Series beradi. Har bir şartni qavsga olib, & dan foydalaning.", + "lesson": "reading-data" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "import pandas as pd\nsales = pd.DataFrame({\"city\": [\"Tashkent\", \"Bukhara\", \"Tashkent\"],\n \"quantity\": [4, 12, 6]})\nprint(sales.groupby(\"city\")[\"quantity\"].sum()[\"Tashkent\"])", + "options": [ + "2", + "4", + "10", + "22" + ], + "answer": 2, + "explanation": "groupby har bir şahar qatorlarini yiğadi, sum() esa Tashkent miqdorlarini qöşadi: 4 + 6.", + "lesson": "pandas-basics" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "import pandas as pd\nsales = pd.DataFrame({\"product\": [\"tea\", \"plov\", \"tea\", \"tea\"]})\ncounts = sales[\"product\"].value_counts()\nprint(counts.index[0], counts.iloc[0])", + "options": [ + "tea 3", + "plov 1", + "tea 1", + "product 4" + ], + "answer": 0, + "explanation": "value_counts() har bir qiymatni sanaydi va eng köp uçraydigandan eng kamiga qarab saralaydi, şuning uçun 3 ta bölgan tea birinçi keladi.", + "lesson": "pandas-basics" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "import pandas as pd\ndf = pd.DataFrame({\"name\": [\" aziza\", \"BEKZOD \"]})\nprint(df[\"name\"].str.strip().str.title().tolist())", + "options": [ + "[' aziza', 'BEKZOD ']", + "AttributeError", + "['aziza', 'bekzod']", + "['Aziza', 'Bekzod']" + ], + "answer": 3, + "explanation": ".str vositasi satr metodlarini ustundagi har bir qiymatga qöllaydi va ularni zanjir qiliş mumkin.", + "lesson": "pandas-basics" + }, + { + "question": "print nimani körsatadi?", + "code": "import pandas as pd\nsales = pd.DataFrame({\"city\": [\"Tashkent\", \"Bukhara\"], \"price\": [15000, 8000]})\nsales[sales[\"city\"] == \"Bukhara\"][\"price\"] = 9000\nprint(sales.loc[1, \"price\"])", + "options": [ + "9000", + "8000", + "KeyError", + "None" + ], + "answer": 1, + "explanation": "Zanjirli indekslaş vaqtinçalik nusxaga qiymat yozadi, şuning uçun asl jadval özgarmaydi. sales.loc[sales[\"city\"] == \"Bukhara\", \"price\"] = 9000 dan foydalaning.", + "lesson": "pandas-basics" + }, + { + "question": "Oxirgi qatorda nima böladi?", + "code": "import matplotlib\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\nfig, ax = plt.subplots()\nax.title(\"Sales\")", + "options": [ + "Sarlavha Sales ga özgaradi", + "AttributeError", + "TypeError", + "plt.show() gaça heç narsa" + ], + "answer": 2, + "explanation": "ax.title metod emas, Text obyekti. Axes da ax.set_title(\"Sales\") dan foydalaning.", + "lesson": "charts-with-matplotlib" + }, + { + "question": "Bir yil davomida kunlik harorat qanday taqsimlanganini körmoqçisiz. Qaysi grafik eng mos?", + "options": [ + "Doiraviy diagramma", + "Gistogramma", + "Oy nomlarining çiziqli grafigi", + "Bitta nuqtali tarqoq nuqtalar grafigi (scatter)" + ], + "answer": 1, + "explanation": "Gistogramma qiymatlarni oraliqlarga (bin) guruhlaydi va har bir oraliq qança tez-tez uçrayotganini körsatadi - bu aynan taqsimot.", + "lesson": "charts-with-matplotlib" + } + ] +} diff --git a/docs/.vitepress/quizzes/uz/module-14.json b/docs/.vitepress/quizzes/uz/module-14.json new file mode 100644 index 0000000..b7a9f51 --- /dev/null +++ b/docs/.vitepress/quizzes/uz/module-14.json @@ -0,0 +1,158 @@ +{ + "module": "14 · Advanced Python (ixtiyoriy)", + "title": "Nazorat: Advanced Python", + "intro": "Dekoratorlar, maʼlumot modeli, kontekst menejerlari va asinxron kodni hamda Python xotira, dizayn patternlar, parallel bajariş va testlaşni qanday boşqarişini tuşunişingizni tekşiring.", + "questions": [ + { + "question": "city(\"Buxoro\") nimani qaytaradi?", + "code": "def bold(func):\n return lambda text: \"\" + func(text) + \"\"\ndef italic(func):\n return lambda text: \"\" + func(text) + \"\"\n@italic\n@bold\ndef city(name): return name", + "options": [ + "\"Buxoro\"", + "\"Buxoro\"", + "\"Buxoro\"", + "\"Buxoro\"" + ], + "answer": 2, + "explanation": "Ketma-ket yozilgan dekoratorlar pastdan yuqoriga qöllanadi, yaʼni city = italic(bold(city)). Eng yuqoridagi italic dekoratori eng taşqi örovçi funksiya böladi.", + "lesson": "closures-and-decorators" + }, + { + "question": "def fetch_rate() ustidagi @retry(times=3) qaysi qatorni anglatadi?", + "options": [ + "fetch_rate = retry(fetch_rate, times=3)", + "fetch_rate = retry(times=3)(fetch_rate)", + "fetch_rate = retry(times=3)", + "fetch_rate = retry(fetch_rate)(times=3)" + ], + "answer": 1, + "explanation": "Avval retry(times=3) bajariladi va u dekorator qaytarişi kerak, keyin şu dekorator funksiya bilan çaqiriladi. Şuning uçun argumentli dekoratorga yana bir daraja iç-iç funksiya kerak.", + "lesson": "closures-and-decorators" + }, + { + "question": "Bu kod nimani çop etadi?", + "code": "class Settings:\n language = \"uz\"\n def __getattr__(self, name):\n return f\"<{name}>\"\ns = Settings()\nprint(s.language, s.theme)", + "options": [ + "uz ", + " ", + "uz, keyin AttributeError", + ", 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 @@ + + + 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 @@ + + +