Python
Klassenstufen: Grade 7 - Grade 8
Bildungssystem: National English
I want a course for teenagers on Python, a programming language
#Learn_programming language
I want a course for teenagers on Python, a programming language
#Learn_programming language
1. Install Python 3.x on the target OS and verify the installation from the terminal (e.g., python --version).
2. Create and activate a virtual environment (python -m venv .venv) and manage dependencies with pip (install, list, freeze).
3. Create, save, and run a Python script from the terminal and within VS Code, confirming correct input/output behavior.
4. Use the Python REPL to test expressions, inspect objects with type(), dir(), and help(), and recall previous commands.
5. Configure VS Code for Python (interpreter selection, extensions) and run/debug a program using breakpoints and variable/watch views.
1. Install Python 3.x on Windows, macOS, or Linux using the official installer or package manager and select the PATH option when appropriate.
2. Verify the installation by running python --version and pip --version from the terminal and capturing the output.
3. Configure system PATH or use py/python3 commands to ensure the correct interpreter is invoked.
4. Locate the Python executable and site-packages folder using where/which and python -m site.
5. Demonstrate opening a terminal (Command Prompt, PowerShell, Terminal) and navigating directories with cd, ls/dir, and pwd.
6. Document installation steps and verification results with screenshots or terminal logs for reproducibility.
1. Launch the Python REPL from the terminal and evaluate arithmetic and string expressions interactively.
2. Inspect objects using type(), dir(), and help() and record findings about common built-ins.
3. Create a hello.py script, run it with python hello.py, and confirm expected input/output behavior.
4. Recall previous REPL commands and edit multi-line input to prototype small snippets efficiently.
5. Use print() and input() in a script to echo user input and handle simple cases.
6. Compare REPL, script, and terminal behaviors by timing quick tests and noting pros/cons for learning.
1. Create a project folder and initialize a virtual environment using python -m venv .venv.
2. Activate and deactivate the virtual environment on Windows, macOS, and Linux shells.
3. Configure the terminal or VS Code to automatically use the project’s .venv interpreter.
4. Explain why isolating dependencies prevents version conflicts across school projects.
5. Confirm the active interpreter path with which/where python and sys.executable in Python.
6. Record environment setup steps in a short checklist saved in the project README.
1. Install, upgrade, and uninstall packages with pip install, pip install -U, and pip uninstall.
2. List installed packages with pip list and freeze exact versions with pip freeze > requirements.txt.
3. Re-create environments on another machine using pip install -r requirements.txt and verify versions.
4. Search for reputable packages on PyPI and evaluate project health using release history and documentation.
5. Pin versions strategically to avoid breaking changes while staying reasonably up-to-date.
6. Troubleshoot common pip errors (permissions, network) and document resolutions for classmates.
1. Install the Python and Pylance extensions and select the correct interpreter in VS Code.
2. Create and run a launch configuration to start a script with arguments from the Run and Debug view.
3. Set breakpoints, step over/into/out, and inspect variables in the debug sidebar and Watch panel.
4. Evaluate expressions in the Debug Console and add conditional breakpoints to isolate issues.
5. Use the Problems panel and terminal integration to streamline edit-run-debug workflows.
6. Capture a short screen recording or annotated screenshots that demonstrate a full debug session.
1. Create a new Jupyter notebook in VS Code or JupyterLab and add code and Markdown cells.
2. Run cells individually, restart the kernel, and re-run the notebook to verify reproducibility.
3. Import and use standard libraries (math, random) in cells to demonstrate quick experimentation.
4. Embed charts or rich output in cells and annotate steps with clear Markdown explanations.
5. Export the notebook to HTML or PDF for sharing with classmates or teachers.
6. Organize notebooks and data files into folders to keep projects tidy and portable.
1. Declare and assign variables with meaningful identifiers; inspect and convert types using type(), int(), float(), and str().
2. Perform arithmetic, comparison, and string operations; format output with f-strings and control precision with round().
3. Manipulate lists, dictionaries, sets, and tuples (index, slice, add/remove/update elements, membership tests) to model simple problems.
4. Acquire input using input(); validate and convert values safely with guard code to prevent crashes from bad input.
5. Import and apply standard modules (e.g., math, random, statistics) to solve computational tasks.
1. Declare variables with descriptive names and assign integers, floats, strings, and booleans.
2. Inspect types using type() and explain when to convert with int(), float(), and str().
3. Apply explicit casting to prevent unintended string concatenation or integer division issues.
4. Compute with mixed numeric types and justify precision choices using round() and formatted output.
5. Compare immutable vs mutable behavior through simple experiments with numbers and strings.
6. Document variable purposes using short comments that clarify meaning and units.
1. Acquire user input with input() and convert to numeric types using defensive try/except blocks.
2. Validate inputs against ranges or allowed options and prompt the user to re-enter invalid values.
3. Format output using f-strings, alignment, and precision controls to create readable messages.
4. Construct simple calculators (e.g., grade average, tip calculator) that handle edge cases gracefully.
1. Implement branching with if/elif/else and boolean logic (and, or, not) to control program behavior.
2. Employ for and while loops to iterate over ranges, strings, and collections; use break and continue appropriately.
3. Apply counting, accumulation, and searching patterns to process data sets correctly and efficiently for the problem scale.
4. Trace program state step-by-step (manually or with a debugger) to predict outputs and detect off-by-one and boundary errors.
5. Refactor repetitive code into clear loop structures and helper logic to reduce duplication.
1. Construct decision structures using if/elif/else to implement branching logic.
2. Combine boolean operators and, or, not to encode multi-condition rules.
3. Trace condition evaluations step-by-step to predict which branch will execute.
4. Apply comparison chaining (a < b < c) for readable range checks.
5. Refactor nested if statements into clearer expressions and early returns where suitable.
6. Validate outcomes with small input tables that exercise all branches.
1. Design decision tables or simple flowcharts before coding to clarify paths.
2. Implement category mapping (e.g., letter grades) with clean elif ladders or dict lookups.
3. Guard against invalid input using combined boolean checks and informative messages.
4. Use ternary expressions for concise assignments when appropriate and readable.
5. Separate decision logic from I/O to make code easier to test and modify.
6. Review and improve condition names to reflect intent (e.g., is_valid_age).
1. Define and call functions with positional, keyword, and default parameters; return values that satisfy the stated contract.
2. Apply local and global scope rules to prevent unintended side effects and name collisions.
3. Document functions and modules using docstrings (PEP 257) and optional type hints to improve readability and tooling support.
4. Organize code into modules and packages; import with aliases and use the if __name__ == '__main__' guard for runnable scripts.
1. Define functions with positional, keyword, and default parameters to support flexible calls.
2. Return computed values that meet a clear contract described in the function name and docstring.
3. Call functions using keyword arguments for clarity and reorderability when helpful.
4. Design examples that show correct outputs for typical and edge inputs to verify contracts.
5. Detect and fix parameter mismatches by reading error messages and adjusting calls.
6. Refactor long scripts into small functions that each do one focused task.
1. Specify preconditions, postconditions, and examples for each function in concise notes.
2. Choose parameter names that communicate units, types, and expected formats.
3. Separate pure logic from input/output to enable straightforward unit tests.
4. Return tuples or dicts when multiple values are needed and explain the choice.
5. Apply default parameters to simplify common calls while keeping flexibility.
6. Evaluate function designs by reviewing clarity, reusability, and testability.
1. Read from and write to text files safely using with open(...) and pathlib.Path for cross-platform file paths.
2. Parse and generate CSV files with the csv module, handling headers and delimiters correctly.
3. Load and dump JSON data to and from Python dictionaries/lists using json.load()/json.dump().
4. Transform datasets using loops and list/dictionary methods (e.g., append, extend, update, get) to filter, aggregate, or reshape records.
5. Handle file-related exceptions (e.g., FileNotFoundError, PermissionError) with try/except to produce informative, user-friendly messages.
1. Read entire files and line-by-line using with open(...) as f and iterate safely.
2. Write and append to text files while ensuring files are closed automatically.
3. Handle encoding explicitly (utf-8) when reading/writing to avoid errors.
4. Normalize newline handling across platforms by using text mode and print(..., file=f).
5. Summarize file read/write results with counts of lines and characters processed.
6. Design a mini log writer that appends timestamped entries.
1. Create Path objects and join paths using the / operator instead of string concatenation.
2. Check file existence, file size, and iterate directory contents using pathlib methods.
3. Build data/output folders inside a project and ensure they exist with mkdir(parents=True, exist_ok=True).
4. Convert relative to absolute paths and display them for verification.
5. Move and copy files safely with replace and write_text/read_text helpers.
6. Refactor string-based path code to pathlib for clarity and portability.
1. Load CSV data into a pandas DataFrame and inspect structure (shape, columns, dtypes) and basic summary info.
2. Filter rows, select columns, sort values, and compute simple aggregates (e.g., mean, count, min/max); create derived columns with vectorized expressions.
3. Generate basic plots (line, bar, histogram) using matplotlib or pandas .plot(); include titles, axis labels, and legends.
4. Export cleaned data and charts to files (e.g., CSV, PNG) with meaningful filenames and organized folders.
5. Justify choices that avoid misleading visuals and respect privacy when using real or shared datasets.
1. Import pandas and load CSV files into DataFrames using pd.read_csv with explicit options.
2. Inspect shape, head/tail, columns, and dtypes to understand structure quickly.
3. Detect missing values and count them per column to assess data quality.
4. Rename columns to clear, student-friendly names and document the mapping.
5. Compute quick summaries (describe, value_counts) to spot distributions and outliers.
6. Log the data loading steps and decisions in a short notebook narrative.
1. Select columns by label and filter rows using boolean masks (e.g., df[df.col > 0]).
2. Sort values by one or more columns and confirm ordering by inspection.
3. Chain operations safely while keeping code readable with intermediate variables.
4. Compute simple aggregates (mean, min, max, count) and compare groups with value_counts.
5. Validate filter results by checking counts before and after operations.
6. Save intermediate results to new CSVs with versioned filenames.
1. Diagnose and fix syntax, runtime, and logic errors using stack traces, strategic print/log statements, and VS Code breakpoints/watch.
2. Write and run basic unit tests (unittest or pytest) that cover typical and edge cases; interpret failures to guide fixes.
3. Enforce code style and readability by applying PEP 8; format with black and identify issues with flake8.
4. Version code with Git: initialize a repository, create branches, make atomic commits with clear messages, and push to GitHub.
5. Maintain a .gitignore and a README that document installation, usage, and testing instructions for the project.
1. Interpret stack traces to identify file, line, and error type quickly.
2. Insert targeted print or logging statements to isolate faulty variables and branches.
3. Reproduce bugs consistently with small inputs to accelerate fixes.
4. Fix common errors (NameError, TypeError, IndexError) and explain the root cause.
5. Create minimal examples that demonstrate a bug separate from the full program.
6. Summarize each fix in commit messages that reference symptoms and cause.
1. Set and manage breakpoints, including conditional and logpoint breakpoints.
2. Inspect call stacks and variable states to follow execution precisely.
3. Step through code to observe control flow and confirm or refute hypotheses.
4. Watch expressions and evaluate small tests in the Debug Console to probe state.
5. Capture and share a short debug session walkthrough with screenshots or video.
6. Reset environments and rerun to validate that the fix works reliably.
5. Log intermediate values with clear labels to support quick manual checks of program logic.
6. Refactor repetitive prompts into helper snippets that reduce duplication.
1. Apply arithmetic operators (+, -, *, /, //, %, **) to solve everyday problems.
2. Use comparison operators (==, !=, <, <=, >, >=) to drive decision-making in small programs.
3. Combine numeric expressions in f-strings to present user-friendly summaries of results.
4. Detect and prevent division-by-zero and overflow-like scenarios with guard code.
5. Benchmark alternative expressions for readability and correctness using small tests.
6. Explain operator precedence and add parentheses to make evaluation order explicit.
1. Slice strings, index characters, and iterate over text to analyze and transform content.
2. Apply common string methods (lower, upper, strip, split, join, replace) to clean inputs.
3. Construct formatted messages using f-strings with numeric and date values.
4. Validate usernames or simple IDs using startswith, isdigit, and length checks.
5. Assemble multi-line messages with newline characters and triple-quoted strings.
6. Compare concatenation vs join for building strings from lists and choose appropriately.
1. Create lists and tuples; index, slice, and iterate to access elements safely.
2. Modify lists using append, extend, insert, remove, pop, and sort for common tasks.
3. Apply membership tests (in, not in) and count occurrences to analyze collections.
4. Build nested lists (matrix-like) for small tables and traverse with nested loops.
5. Choose tuples for fixed records (e.g., coordinate pairs) and justify immutability benefits.
6. Design small programs (e.g., to-do tracker) that manipulate lists predictably.
1. Create dictionaries; add, update, and delete entries using assignment, update, and del.
2. Retrieve values safely with get and setdefault to avoid KeyError and simplify logic.
3. Apply sets for uniqueness checks and operations (union, intersection, difference).
4. Import math, random, and statistics and apply functions to solve basic tasks.
5. Model real items (e.g., student records) with dicts and iterate over keys, values, items.
6. Select the right collection type by evaluating lookup speed, order needs, and uniqueness.
1. Iterate over ranges, strings, lists, and dicts using for loops with clear loop variables.
2. Implement while loops with well-defined termination conditions and safeguards.
3. Apply break and continue to manage control flow responsibly within loops.
4. Generate index-element pairs with enumerate to simplify access to positions.
5. Use zip to traverse multiple sequences in lockstep and avoid index errors.
6. Benchmark for vs while choices for clarity and correctness in small tasks.
1. Implement counters and accumulators to compute totals, averages, and frequencies.
2. Search for items that match criteria and exit early when found to save work.
3. Traverse collections to compute min/max with explicit comparisons and guard code.
4. Aggregate values by category using dicts and sets for efficient lookups.
5. Compare loop-based solutions to built-in methods (sum, min, max) for readability.
6. Validate loop boundaries to prevent off-by-one errors with small test cases.
1. Trace variable changes line-by-line using hand traces and print-based checkpoints.
2. Predict outputs for given inputs and verify predictions by running the program.
3. Identify boundary cases (empty list, first/last index) and test them explicitly.
4. Detect and correct off-by-one errors by inspecting loop start, stop, and step.
5. Explain the cause of a logic error in plain language and propose a minimal fix.
6. Summarize lessons learned from a trace in a brief reflection for future reference.
1. Identify duplicated code and consolidate it into loops or small helper blocks.
2. Replace complex nested loops with clearer structures or early-continue patterns.
3. Extract reusable logic into small helper snippets to reduce cognitive load.
4. Name loop variables and helpers descriptively to clarify intent for readers.
5. Measure improvements by comparing lines of code and readability before and after.
6. Review peer code and suggest loop refactors with concrete examples.
1. Differentiate local, global, and nonlocal scope in code examples.
2. Prevent unintended shadowing by renaming variables and reducing global state.
3. Apply the global keyword only when absolutely necessary and justify its use.
4. Illustrate lifetime of variables within functions and modules using prints or traces.
5. Encapsulate state within functions to avoid cross-function interference.
6. Refactor code that mutates shared data into safer, clearer patterns.
1. Write function and module docstrings following PEP 257 conventions with examples.
2. Use Sphinx or Google-style sections (Args, Returns, Raises) for clarity in docstrings.
3. Add basic type hints for parameters and return types to improve editor assistance.
4. Run tools or IDE features to view rendered docstrings and type information.
5. Detect and fix mismatches between hints and actual returned values.
6. Publish a mini reference (README + examples) documenting a small utility module.
1. Split code into multiple .py files by feature and import with and without aliases.
2. Create a simple package folder with __init__.py and demonstrate relative imports.
3. Explain circular import risks and restructure modules to remove cycles.
4. Use from module import name and import module as alias appropriately for readability.
5. Bundle reusable utilities into a package-like folder and import them in a demo app.
6. Document the module layout in a short diagram or tree for teammates.
1. Add the if __name__ == '__main__' guard to separate library code from run logic.
2. Parse simple command-line arguments with sys.argv to customize script behavior.
3. Log a clear startup message and exit status for easier troubleshooting.
4. Invoke main() from the guard and return exit codes that reflect success/failure.
5. Demonstrate importing the script’s functions from another file without executing main().
6. Package a small project with a runnable entry and a separate module of helpers.
1. Read CSV files with csv.reader and csv.DictReader and handle headers correctly.
2. Write CSV files with csv.writer and csv.DictWriter including headers and custom delimiters.
3. Clean and convert fields (e.g., to int/float) while reading rows to ensure valid data types.
4. Detect and handle malformed rows by skipping or reporting them clearly.
5. Aggregate simple statistics (count, min, max) while streaming rows to avoid excess memory use.
6. Export filtered rows to a new CSV with a meaningful filename pattern.
1. Load JSON from files and strings into Python dict/list structures using json.load/json.loads.
2. Access nested data safely using get with defaults and guard checks for missing keys.
3. Transform Python objects into JSON with json.dump/json.dumps and pretty printing (indent).
4. Validate JSON structure with simple assertions or try/except around json.loads.
5. Round-trip small datasets from dict -> JSON -> dict and confirm equality semantically.
6. Compare CSV vs JSON trade-offs for tabular vs nested data and choose appropriately.
1. Filter records based on conditions and compute aggregates using accumulation patterns.
2. Reshape lists of dicts by selecting columns and renaming keys consistently.
3. Combine datasets by key using dicts or lookups and document merge assumptions.
4. Apply list and dict comprehensions for concise data transformations where readable.
5. Measure transformation correctness by checking record counts before and after.
6. Write results to disk and verify by reloading and spot-checking sample rows.
1. Catch FileNotFoundError and PermissionError and display clear next-step guidance.
2. Differentiate exception types to tailor messages and suggested fixes for users.
3. Log root cause details while presenting a simple message to non-technical users.
4. Implement a safe open_file helper that wraps open with robust error handling.
5. Create small tests that simulate missing files and confirm graceful behavior.
6. Summarize error-handling strategies in the project README for classmates.
1. Compute column-wise aggregates and store results in variables for reporting.
2. Group by a single categorical column and compute counts or means as appropriate.
3. Handle missing values before aggregation using fillna or dropna with justification.
4. Compare manual loops to pandas vectorized operations for speed and clarity on small data.
5. Export group summaries to CSV and reload to confirm consistency.
6. Explain when grouping adds value vs when a simple aggregate is sufficient.
1. Construct derived columns using arithmetic and conditional expressions (np.where/map).
2. Normalize or scale numeric columns with simple formulas and explain their purpose.
3. Parse dates and extract parts (year, month) for time-based analysis.
4. Validate new columns by spot-checking a few rows and recalculating manually.
5. Drop intermediate columns to keep DataFrames tidy and reproducible.
6. Document transformation steps in Markdown cells for classmates to follow.
1. Generate line, bar, and histogram plots using pandas .plot and matplotlib functions.
2. Label axes, add titles and legends, and apply readable color choices for clarity.
3. Adjust figure size and layout to fit typical school report pages.
4. Export plots to PNG/SVG with consistent filenames and folder structure.
5. Compare different chart types for the same data and justify the best choice.
6. Annotate charts to highlight key findings with arrows or text notes.
1. Package cleaned data, charts, and a brief summary into a shareable folder.
2. Write a short findings summary that states insights without overstating causation.
3. Apply privacy practices by removing direct identifiers and aggregating small groups.
4. Avoid misleading visuals by selecting correct scales and avoiding cherry-picked ranges.
5. Cite data sources and note limitations transparently in the notebook or README.
6. Submit a mini data story that a non-technical peer can follow and critique constructively.
1. Structure tests in a tests/ folder and name files/functions following conventions.
2. Write test cases that cover typical and edge inputs for pure functions.
3. Use setUp/tearDown to prepare and clean test fixtures when needed.
4. Run tests from the terminal and interpret failures to guide code changes.
5. Measure coverage informally by listing functions and scenarios exercised.
6. Refactor code to improve testability by reducing side effects and I/O in logic.
1. Install pytest in a virtual environment and run tests with pytest -q.
2. Write concise tests using assert statements and parametrize to cover multiple cases.
3. Organize tests with fixtures for reusable data and temporary files.
4. Mark and skip tests conditionally to focus on relevant checks during development.
5. Capture exceptions with pytest.raises to verify error handling paths.
6. Compare unittest and pytest ergonomics and choose based on project needs.
1. Configure black and apply formatting to a project consistently from the terminal or VS Code.
2. Explain key PEP 8 rules (naming, line length, imports) and enforce them in examples.
3. Refactor long lines and complex expressions to improve readability without changing behavior.
4. Create a pyproject.toml to store black configuration for team use.
5. Run black in check mode in a pre-commit step or simple script for consistency.
6. Review diffs to confirm only formatting changed, not logic.
1. Install and run flake8 to report style and simple correctness issues.
2. Fix reported issues (unused variables, unreachable code) and justify changes.
3. Suppress false positives responsibly with inline comments and explanations.
4. Adopt import ordering and spacing conventions that aid scanning and reviews.
5. Document team style rules in the README for quick onboarding.
6. Integrate linting into a simple task script or VS Code problem matcher.
1. Initialize a Git repository, stage changes, and create meaningful atomic commits.
2. Write clear, imperative commit messages that reference the what and why.
3. Inspect history with git log and diffs with git diff to review changes.
4. Revert mistakes safely with git restore or git revert and explain the choice.
5. Maintain a .gitignore tailored for Python (venv, __pycache__, data outputs).
6. Tag a simple release and explain its purpose to classmates.
1. Create and switch branches to isolate features or fixes from main.
2. Merge branches with fast-forward or merge commits and resolve simple conflicts.
3. Create a GitHub repository, push local commits, and set the remote origin.
4. Open a pull request and request a peer review with a checklist for testing.
5. Write a README with setup, usage, and testing instructions suitable for new contributors.
6. Protect main by agreeing on a basic workflow (PRs, reviews) for class projects.