Skip to content

Latest commit

 

History

History
962 lines (569 loc) · 38.2 KB

0.md

File metadata and controls

962 lines (569 loc) · 38.2 KB

BLOK 0 — Środowisko i warsztat programisty

BLOCK 0 — Developer Environment and Workflow Basics


A few words about programming / Kilka słów o programowaniu

1. Knowing the language basics — understanding syntax, loops, conditions, functions (like learning grammar in a foreign language).

1. Znajomość podstaw języka — rozumienie składni, pętli, warunków, funkcji (jak nauka gramatyki w języku obcym).

2. Understanding design patterns and principles — learning design patterns and general programming principles that keep code maintainable and testable.

2. Rozumienie wzorców projektowych i zasad — poznawanie wzorców projektowych i ogólnych zasad programowania, które sprawiają, że kod pozostaje łatwy w utrzymaniu i testowalny.

3. Working with libraries — most code you'll use comes from libraries (pre-written packages).

3. Praca z bibliotekami — większość kodu, którego użyjesz, pochodzi z bibliotek (gotowych pakietów).

This is faster than writing everything yourself, usually better tested (many users find and fix bugs), and often gives you extra features for free.

To jest szybsze niż pisanie wszystkiego samemu, zazwyczaj lepiej przetestowane (wielu użytkowników znajduje i naprawia błędy) i często daje ci dodatkowe funkcje za darmo.

It's like cooking with pre-made ingredients instead of growing everything from scratch.

To jak gotowanie z gotowych składników zamiast uprawiania wszystkiego od zera.

4. Connecting ideas to working code — turning a concept into a plan, sketching how it should work, picking the right libraries, and writing your own code to tie it all together.

4. Łączenie pomysłów z działającym kodem — zamienianie koncepcji w plan, szkicowanie jak ma działać, wybieranie odpowiednich bibliotek i pisanie własnego kodu, który łączy to wszystko razem.

This is where you spend most of your time — combining existing tools in new ways to solve specific problems.

Tu spędzasz większość czasu — łączysz istniejące narzędzia na nowe sposoby, by rozwiązać konkretne problemy.

5. Reading more than writing — you'll spend much more time reading code and documentation than writing new code.

5. Czytanie więcej niż pisanie — spędzisz znacznie więcej czasu na czytaniu kodu i dokumentacji niż na pisaniu nowego kodu.

The work involves many activities in different proportions: reading existing code > planning and requirements gathering > reading documentation > debugging and testing > writing new code.

Praca obejmuje wiele aktywności w różnych proporcjach: czytanie istniejącego kodu > planowanie i zbieranie wymagań > czytanie dokumentacji > debugowanie i testowanie > pisanie nowego kodu.

6. Maintaining and troubleshooting — after writing code, you'll spend time maintaining it and debugging to find root causes of issues.

6. Utrzymanie i rozwiązywanie problemów — po napisaniu kodu spędzisz czas na jego utrzymaniu i debugowaniu, by znaleźć przyczyny błędów.

Code needs updates when requirements change, bugs appear, or dependencies get updated. Finding why something breaks often takes longer than fixing it.

Kod wymaga aktualizacji gdy wymagania się zmieniają, błędy się pojawiają lub zależności są aktualizowane. Znalezienie dlaczego coś nie działa często zajmuje dłużej niż naprawa.


Cel / Goal

PL: Nauczyć się przygotować kompletne środowisko do pracy w Pythonie: zainstalować narzędzia, korzystać z IDE, uv, Git i Docker, pisać pierwszy test oraz uruchomić debugger.
EN: Learn how to set up a complete Python development environment: install tools, use an IDE, uv, Git and Docker, write your first test, and run the debugger.


💡 1️⃣ Python & pyenv – wersje języka / Python & pyenv – Language Versions

Python comes in multiple versions (e.g. 3.9, 3.11, 3.14).

Python to język, który występuje w różnych wersjach (np. 3.9, 3.11, 3.14).

pyenv lets you install and switch between them without conflicts — similar to how you can have multiple versions of Office (2016, 2019, 2021) on one computer.

pyenv pozwala zainstalować kilka wersji i przełączać się między nimi bez konfliktów — podobnie jak możesz mieć kilka wersji Office'a (2016, 2019, 2021) na jednym komputerze.

📘 Official documentation / Oficjalna dokumentacja:

pyenv README (GitHub)

Read sections: "Installation" and "Usage" / Przeczytaj sekcje: "Installation" i "Usage"

Why it matters / Dlaczego to ważne:

Some projects need older or newer Python versions. pyenv ensures each project uses exactly the right one.

Niektóre projekty wymagają starszych lub nowszych wersji Pythona. pyenv zapewnia, że każdy projekt używa dokładnie tej, której potrzebuje.

Zadanie / Task:

pyenv install 3.14
pyenv global 3.14
python --version

Make sure the output shows Python 3.14.x (where x is the latest patch version).

Upewnij się, że wynik to Python 3.14.x (gdzie x to najnowsza wersja poprawek).

Expected output / Oczekiwany rezultat:

Python 3.14.0

Note: The exact version may be newer (e.g., 3.14.1) depending on the latest release. See Python version history.

Uwaga: Dokładna wersja może być nowsza (np. 3.14.1) w zależności od najnowszego wydania. Zobacz historię wersji Pythona.


💡 2️⃣ IDE – Twoje główne narzędzie pracy / IDE – Your Main Working Tool

An IDE (Integrated Development Environment) is like MS Word or OpenOffice for programmers – a place where you write, run, and test code.

IDE (Integrated Development Environment) to coś jak MS Word lub OpenOffice dla programistów – miejsce, w którym piszesz, uruchamiasz i testujesz kod.

An IDE can:

IDE potrafi:

  • highlight syntax / kolorować składnię
  • suggest code completions (IntelliSense) / podpowiadać kod (tzw. IntelliSense)
  • help you debug step-by-step / pomagać w debugowaniu (śledzeniu krok po kroku)
  • integrate with Git and testing tools / integrować się z Gitem i testami

Why it matters / Dlaczego to ważne:

A good IDE helps you write code faster, catch errors early (similar to how Word highlights spelling or grammar errors), and provides useful programming tools with extensibility through plugins.

Dobre IDE pozwala szybciej pisać kod, wychwytuje błędy wcześnie (podobnie jak Word podkreśla błędy ortograficzne czy gramatyczne), dostarcza narzędzi przydatnych przy programowaniu i pozwala na rozszerzalność przez pluginy.


🔧 Rekomendowane IDE / Recommended IDEs

Narzędzie / Tool Opis / Description Link
PyCharm Community pełne IDE dla Pythona – debugger, testy, Git, integracja z venv https://www.jetbrains.com/pycharm/download
VS Code lżejsze, uniwersalne IDE z wtyczkami do Pythona https://code.visualstudio.com/
Jupyter Notebook interaktywne środowisko do nauki i analizy danych – łączy kod, wyniki i dokumentację w jednym miejscu https://jupyter.org/
Google Colab Jupyter w chmurze Google – nie wymaga instalacji, działa w przeglądarce https://colab.research.google.com/

Which one to choose? / Który wybrać?

  • PyCharm — best for complete projects with multiple files, testing, and debugging

    PyCharm — najlepszy do kompletnych projektów z wieloma plikami, testami i debugowaniem

  • VS Code — lightweight and flexible, good for various programming languages

    VS Code — lekkie i elastyczne, dobre dla różnych języków programowania

  • Jupyter Notebook / Google Colab — run code in small chunks (cells) and see results immediately, perfect for learning and experimentation. Try Colab in your browser without installing anything.

    Jupyter Notebook / Google Colab — uruchamiaj kod w małych fragmentach (celach) i widzieć wyniki od razu, idealne do nauki i eksperymentowania. Wypróbuj Colab w przeglądarce bez instalowania czegokolwiek.

🎥 Do obejrzenia / Watch:

📘 Do przeczytania / Read:

🧠 Zadania / Tasks:

  1. Install PyCharm Community from the link above.

    Zainstaluj PyCharm Community z linku powyżej.

  2. Create a new project named hello_world (File → New Project).

    Utwórz nowy projekt o nazwie hello_world (File → New Project).

  3. Check IntelliSense suggestions — type pri... and notice how the IDE suggests print().

    Sprawdź podpowiedzi IntelliSense — wpisz pri... i zauważ, jak IDE podpowiada print().

  4. Write the code:

    Napisz kod:

    print("Hello, world!")
  5. Run the program (green ▶ button or Shift+F10) and check the console output.

    Uruchom program (zielony przycisk ▶ lub Shift+F10) i sprawdź wynik w konsoli.

Expected output / Oczekiwany rezultat:

Hello, world!

💡 3️⃣ uv – menedżer środowisk i paczek / uv – Environment & Package Manager

uv is a modern, ultra-fast environment and package manager.

uv to nowoczesny, bardzo szybki menedżer środowisk i bibliotek.

It combines the functions of older tools (pip, venv, poetry) into one command — like a smart project manager that not only installs tools but also creates a dedicated workspace and tracks what you need.

Łączy funkcje starszych narzędzi (pip, venv, poetry) w jednym poleceniu — jak mądry kierownik projektu, który nie tylko instaluje narzędzia, ale też tworzy dedykowane miejsce pracy i śledzi czego potrzebujesz.

With uv, you don't have to manually create .venv directories — it handles everything automatically.

Dzięki uv nie musisz ręcznie tworzyć katalogów .venv — wszystko robi automatycznie.

📘 Documentation / Dokumentacja:

uv Getting Started (Astral)

Read sections: "Installation" and "Creating a project" / Przeczytaj sekcje: "Installation" i "Creating a project"

Why it matters / Dlaczego to ważne:

Each project may need different library versions. uv creates isolated environments so dependencies never clash.

Każdy projekt może wymagać innych wersji bibliotek. uv tworzy oddzielne środowisko dla każdego projektu, dzięki czemu nie ma konfliktów.


📦 Instalacja uv / Installing uv

Before you can use uv, you need to install it on your system.

Zanim zaczniesz używać uv, musisz go zainstalować w swoim systemie.

Windows:

# Using PowerShell / Używając PowerShell
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

macOS / Linux:

# Using curl / Używając curl
curl -LsSf https://astral.sh/uv/install.sh | sh

Alternative: Using pip (if Python is already installed)

Alternatywnie: Używając pip (jeśli Python jest już zainstalowany)

pip install uv

After installation, verify that uv is installed:

Po instalacji sprawdź, czy uv jest zainstalowany:

uv --version

Expected output / Oczekiwany rezultat:

uv 0.5.0 (or newer / lub nowsza wersja)

📘 More installation options / Więcej opcji instalacji:

See uv Installation Guide for other methods (Homebrew, Scoop, etc.).

Zobacz przewodnik instalacji uv dla innych metod (Homebrew, Scoop, itp.).


📚 Co to są biblioteki i paczki? / What Are Libraries and Packages?

A library (or package) is a collection of pre-written code that saves you time — like an app store for programmers.

Biblioteka (ang. library lub package) to zbiór gotowego kodu, który oszczędza Ci czas — jak sklep z aplikacjami dla programistów.

For example, requests simplifies web downloads, and pandas helps analyze data.

Np. requests ułatwia pobieranie danych z Internetu, a pandas pomaga analizować dane.

Adding libraries extends your program's functionality without writing everything from scratch.

Dodając biblioteki, rozszerzasz możliwości swojego programu bez pisania wszystkiego od zera.


🔍 Gdzie znajdować pakiety? / Where to Find Packages?

PyPI (Python Package Index) is the official repository for Python packages — like Google Play or App Store, but for Python libraries.

PyPI (Python Package Index) to oficjalne repozytorium pakietów Pythona — jak Google Play lub App Store, ale dla bibliotek Pythona.

How to search for packages / Jak wyszukiwać pakiety:

  1. Search on PyPI website: Go to pypi.org and use the search bar.

    Szukaj na stronie PyPI: Przejdź na pypi.org i użyj paska wyszukiwania.

  2. Check package details: Click on a package to see its description, version history, and documentation.

    Sprawdź szczegóły pakietu: Kliknij na pakiet, aby zobaczyć jego opis, historię wersji i dokumentację.

  3. Verify package quality: Look for indicators like download count, last update date, and GitHub stars.

    Zweryfikuj jakość pakietu: Sprawdź wskaźniki jak liczba pobrań, data ostatniej aktualizacji i liczba gwiazdek na GitHubie.

How to check package versions / Jak sprawdzać wersje pakietów:

# Check installed package version / Sprawdź zainstalowaną wersję pakietu
uv pip show requests

# List all installed packages / Wyświetl wszystkie zainstalowane pakiety
uv pip list

# Check for outdated packages / Sprawdź przestarzałe pakiety
uv pip list --outdated

Example: Finding a package for working with dates

Przykład: Wyszukiwanie pakietu do pracy z datami

  1. Search "python date manipulation" on PyPI → Find arrow or python-dateutil

    Wyszukaj "python date manipulation" na PyPI → Znajdziesz arrow lub python-dateutil

  2. Compare packages by checking their PyPI pages for popularity and recent updates

    Porównaj pakiety sprawdzając ich strony PyPI pod kątem popularności i świeżości aktualizacji

  3. Install with: uv add arrow

    Zainstaluj przez: uv add arrow


⚙️ uv vs pip – Różnice / Differences

Narzędzie / Tool Co robi / What it does Różnica / Difference
pip install requests Instaluje bibliotekę / Installs library Tylko instalacja — musisz ręcznie zaktualizować requirements.txt / Just installs — you must manually update requirements.txt
uv add requests Instaluje i aktualizuje pyproject.toml / Installs and updates pyproject.toml Automatyczna dokumentacja zależności / Automatic dependency tracking

⚠️ Note / Uwaga:

Older tutorials use pip install .... Modern projects use uv add ....

Starsze tutoriale używają pip install .... Nowoczesne projekty używają uv add ....


🧩 Zadanie / Task

uv init my_project
cd my_project
uv add requests
uv run python -c "import requests; print(requests.__version__)"

Notice that uv automatically created the .venv directory and pyproject.toml file.

Zauważ, że uv automatycznie utworzył katalog .venv i plik pyproject.toml.

Expected output / Oczekiwany rezultat:

2.31.0  # (or newer version / lub nowsza wersja)

Check that pyproject.toml now contains requests in the dependencies.

Sprawdź, że pyproject.toml zawiera teraz requests w zależnościach.


💡 4️⃣ Git i GitHub – historia i kopie kodu / Git and GitHub – Code History & Backups

Git is a version-control system — like "Track Changes" in Word, but for code.

Git to system śledzenia zmian w kodzie — jak "Śledzenie zmian" w Wordzie, ale dla kodu.

GitHub is the cloud platform to host your code — like Google Drive or Dropbox for programmers.

GitHub to chmura, w której przechowujesz projekty — jak Google Drive lub Dropbox dla programistów.

It lets you undo changes, collaborate with others, and keep an online backup.

Pozwala cofać zmiany, współpracować z innymi i mieć kopię zapasową online.

📘 Article / Artykuł:

Atlassian – What is Git?

Read sections: "What is Git?" and "Why Git for your organization" / Przeczytaj sekcje: "What is Git?" i "Why Git for your organization"

🎥 Video / Wideo:

Tech With Tim – Git Crash Course

Why it matters / Dlaczego to ważne:

Without Git it's easy to overwrite or lose work. With Git you can always roll back to a previous version safely.

Bez Gita łatwo coś nadpisać lub stracić. Z Gitem zawsze możesz bezpiecznie wrócić do wcześniejszej wersji.


🛠️ GitHub CLI (gh) – łatwiejszy sposób pracy z GitHubem / Easier Way to Work with GitHub

GitHub CLI is a command-line tool that simplifies working with GitHub — instead of using the web interface, you can create repositories, pull requests, and manage issues directly from your terminal.

GitHub CLI to narzędzie wiersza poleceń, które upraszcza pracę z GitHubem — zamiast używać interfejsu webowego, możesz tworzyć repozytoria, pull requesty i zarządzać problemami bezpośrednio z terminala.

Installation / Instalacja:

Windows:

# Using WinGet / Używając WinGet
winget install --id GitHub.cli

# Using Scoop / Używając Scoop
scoop install gh

macOS:

# Using Homebrew / Używając Homebrew
brew install gh

Linux:

# Debian/Ubuntu
sudo apt install gh

# Fedora/RHEL
sudo dnf install gh

Alternative: Download from the website

Alternatywnie: Pobierz ze strony

Visit cli.github.com for installers.

Odwiedź cli.github.com aby pobrać instalatory.

Verify installation / Sprawdź instalację:

gh --version

Authenticate with GitHub / Zaloguj się do GitHuba:

gh auth login

Follow the prompts to connect your GitHub account.

Postępuj zgodnie z instrukcjami, aby połączyć swoje konto GitHub.

Why use gh? / Dlaczego używać gh?

  • Faster: Create repos with one command instead of clicking through the web UI

    Szybciej: Twórz repozytoria jedną komendą zamiast klikać po interfejsie webowym

  • Integrated: Works seamlessly with git commands

    Zintegrowany: Działa płynnie z poleceniami git

  • Powerful: Manage issues, PRs, releases all from terminal

    Potężny: Zarządzaj problemami, PR-ami, wydaniami z terminala


.gitignore – which files to ignore / które pliki ignorować

.gitignore tells Git which files not to track — like virtual environments (.venv/), cache files (__pycache__/), and secrets (.env).

.gitignore mówi Gitowi, których plików nie śledzić — jak środowiska wirtualne (.venv/), pliki cache (__pycache__/) i sekrety (.env).

Why: Prevents committing large, auto-generated, or sensitive files. Use GitHub's Python template when creating a repo.

Dlaczego: Zapobiega commitowaniu dużych, automatycznie generowanych lub wrażliwych plików. Użyj szablonu Python podczas tworzenia repo na GitHubie.


README.md – your project's homepage / strona główna projektu

README.md is the first thing people see on your GitHub repo — describes what the project does, how to install it, and how to use it.

README.md to pierwsza rzecz, którą ludzie widzą w Twoim repo na GitHubie — opisuje co robi projekt, jak go zainstalować i jak używać.

Why: Good documentation helps others (and future you) understand and use your code. GitHub displays it automatically on your repo page.

Dlaczego: Dobra dokumentacja pomaga innym (i przyszłemu Tobie) zrozumieć i używać Twojego kodu. GitHub wyświetla go automatycznie na stronie repo.


Zadanie / Task:

Practice the basic Git workflow: create a repository, make commits, push to GitHub, and pull changes.

Przećwicz podstawowy przepływ pracy z Gitem: utwórz repozytorium, wykonaj commity, wypchnij na GitHuba i pobierz zmiany.

Step 1: Create a local repository / Utwórz lokalne repozytorium

mkdir my-first-repo
cd my-first-repo
git init
echo "# My First Repo" > test.txt

Step 2: Make your first commit / Wykonaj pierwszy commit

git add test.txt
git commit -m "Add test file"
git log  # See your commit history / Zobacz historię commitów

Step 3: Create GitHub repository and push / Utwórz repozytorium na GitHubie i wypchnij

Create a new repository on GitHub, then:

Utwórz nowe repozytorium na GitHubie, następnie:

git branch -M main
git remote add origin https://github.com/username/my-first-repo.git
git push -u origin main

Replace username with your GitHub username.

Zamień username na swoją nazwę użytkownika GitHub.

Step 4: Make changes and push again / Wprowadź zmiany i wypchnij ponownie

echo "New line" >> test.txt
git add test.txt
git commit -m "Update test file"
git push

Step 5: Pull changes (simulate collaboration) / Pobierz zmiany (symulacja współpracy)

Edit test.txt directly on GitHub (click file → Edit), then:

Edytuj test.txt bezpośrednio na GitHubie (kliknij plik → Edit), następnie:

git pull  # Download changes from GitHub / Pobierz zmiany z GitHuba

Alternative: Use GitHub CLI / Alternatywnie: Użyj GitHub CLI

mkdir my-first-repo && cd my-first-repo
echo "# My First Repo" > test.txt
git init
git add test.txt
git commit -m "Initial commit"
gh repo create my-first-repo --public --source=. --push

Expected result / Oczekiwany rezultat:

You've learned: git init, git add, git commit, git push, git pull, and git log.

Nauczyłeś się: git init, git add, git commit, git push, git pull i git log.


💡 5️⃣ Debugging and Logging / Debugowanie i logowanie

The simplest way to check what your code does is with print() or pprint() (pretty print for complex data).

Najprostszy sposób, by sprawdzić co robi Twój kod, to print() lub pprint() (ładniejsze formatowanie złożonych danych).

It works, but it quickly becomes messy and hard to maintain or update.

To działa, ale szybko staje się nieczytelne i trudne w zarządzaniu i aktualizacji.

In practice, it's better to use a debugger (like in PyCharm) and the logging module, which let you inspect program behavior without cluttering code with prints.

W praktyce lepiej korzystać z debuggera (np. w PyCharm) oraz modułu logging, które pozwalają analizować działanie programu bez zaśmiecania kodu printami.


🔍 Comparison: print vs pprint vs logging vs debugger

🔍 Porównanie: print vs pprint vs logging vs debugger

Narzędzie / Tool Kiedy używać / When to use Zalety / Pros Wady / Cons
print() Szybki test / Quick check Natychmiastowy rezultat / Immediate result Zaśmieca kod, trudny do wyłączenia / Clutters code, hard to disable
pprint() Złożone struktury danych / Complex data Czytelny format / Readable format Jak print — trudny do zarządzania / Like print — hard to manage
logging Produkcja, długoterminowe śledzenie / Production, long-term tracking Poziomy ważności, zapis do pliku / Severity levels, file output Wymaga konfiguracji / Requires setup
Debugger Szczegółowa analiza / Deep analysis Krok po kroku, brak zmian w kodzie / Step-by-step, no code changes Wymaga nauki / Learning curve

🪄 Debugger

A debugger lets you pause execution anywhere, inspect variable values, and step through code line by line.

Debugger pozwala zatrzymać program w dowolnym miejscu, podejrzeć wartości zmiennych i przejść linijka po linijce.

📘 Official Guide / Oficjalny przewodnik:

PyCharm Debugging Code (JetBrains Docs)

Read sections: "Debugging" and "Stepping through the program" / Przeczytaj sekcje: "Debugging" i "Stepping through the program"

🎥 Video / Wideo:

Corey Schafer – Debugging with PyCharm (0:00–8:00)

Shows how to set breakpoints, track variables, and resume execution / Zobacz jak ustawić breakpoint, śledzić zmienne i wznowić wykonywanie

Why it matters / Dlaczego to ważne:

Debugging helps you precisely see how your code behaves and what variable values are at each step.

Debugowanie pozwala dokładnie zobaczyć, jak zachowuje się Twój kod i jakie są wartości zmiennych w każdym momencie.


🧾 Logging

The logging module is used to record what the program is doing — either on screen or to a file.

Moduł logging służy do zapisywania informacji o tym, co robi program — na ekranie lub w pliku.

It lets you control the level of detail (DEBUG, INFO, WARNING, ERROR, CRITICAL) and easily log exceptions.

Pozwala kontrolować poziom szczegółowości komunikatów (DEBUG, INFO, WARNING, ERROR, CRITICAL) oraz łatwo rejestrować wyjątki.

You can also decide whether logs should be written to a file, displayed on the screen, or both.

Można też ustawić, czy logi mają być zapisywane do pliku, wyświetlane na ekranie, lub oba jednocześnie.

🧩 Zadanie / Task:

Create a file debug_demo.py:

Utwórz plik debug_demo.py:

import logging
from pprint import pprint

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
    handlers=[
        logging.FileHandler("app.log"),  # zapis do pliku / log to file
        logging.StreamHandler()          # pokazuj na ekranie / show on screen
    ]
)

logging.info("Program started")

x = 10
y = 0

# Proste sprawdzenie / Simple check
print(f"{x=}, {y=}")
pprint({"x": x, "y": y})
logging.info(f"{x=}, {y=}")

try:
    result = x / y
except ZeroDivisionError as e:
    logging.exception("Division by zero occurred!")
finally:
    logging.info("Program finished")

Run the program and check both the console output and the app.log file.

Uruchom program i sprawdź zarówno wynik w konsoli, jak i plik app.log.

Expected output / Oczekiwany rezultat:

x=10, y=0
{'x': 10, 'y': 0}
2025-01-15 10:30:45,123 [INFO] x=10, y=0
2025-01-15 10:30:45,124 [ERROR] Division by zero occurred!
Traceback (most recent call last):
  ...
ZeroDivisionError: division by zero
2025-01-15 10:30:45,125 [INFO] Program finished

Check that app.log file was created with the same log messages.

Sprawdź, że plik app.log został utworzony z tymi samymi wiadomościami logów.


🧠 Why this matters / Dlaczego to ważne:

print() and pprint() are fine for quick checks — fast but unstructured.

print() i pprint() są dobre do szybkich testów — szybkie, ale niekontrolowane.

logging lets you centrally manage messages, write them to files, and automatically capture exceptions.

logging pozwala centralnie zarządzać komunikatami, zapisywać je do plików i automatycznie rejestrować wyjątki.

A debugger shows the detailed execution flow and variable state without modifying code.

Debugger pokazuje szczegółowy przebieg programu i stan zmiennych bez zmiany kodu.


🐛 Zadanie z debugowaniem / Debugging Task

Now let's practice using the PyCharm debugger with the same debug_demo.py file.

Teraz przećwiczmy używanie debuggera PyCharm z tym samym plikiem debug_demo.py.

Step 1: Set a breakpoint / Ustaw breakpoint

  1. Open debug_demo.py in PyCharm.

    Otwórz debug_demo.py w PyCharm.

  2. Click in the left margin (gutter) next to line x = 10 — a red dot appears.

    Kliknij w lewym marginesie obok linii x = 10 — pojawi się czerwona kropka.

  3. This is a breakpoint — the program will pause here when you run the debugger.

    To jest breakpoint — program zatrzyma się tutaj gdy uruchomisz debugger.

Step 2: Run the debugger / Uruchom debugger

  1. Right-click on debug_demo.py in the editor.

    Kliknij prawym przyciskiem na debug_demo.py w edytorze.

  2. Select "Debug 'debug_demo'" (or press Shift+F9).

    Wybierz "Debug 'debug_demo'" (lub naciśnij Shift+F9).

  3. The program runs and stops at the breakpoint.

    Program uruchamia się i zatrzymuje na breakpoincie.

Step 3: Inspect variables / Sprawdź zmienne

  1. Look at the "Variables" panel at the bottom — you'll see x and y with their current values.

    Spójrz na panel "Variables" na dole — zobaczysz x i y z ich aktualnymi wartościami.

  2. Notice that y = 0 — this will cause the ZeroDivisionError later!

    Zauważ, że y = 0 — to spowoduje ZeroDivisionError później!

Step 4: Step through the code / Przejdź krok po kroku

Use these buttons in the debug toolbar:

Użyj tych przycisków na pasku debugowania:

  • Step Over (F8) — execute current line and move to the next

    Step Over (F8) — wykonaj bieżącą linię i przejdź do następnej

  • Step Into (F7) — enter into function calls

    Step Into (F7) — wejdź do wywołań funkcji

  • Resume (F9) — continue until next breakpoint or end

    Resume (F9) — kontynuuj do następnego breakpointa lub końca

Step 5: Watch the exception / Obserwuj wyjątek

  1. Press F8 (Step Over) multiple times to reach the try block.

    Naciśnij F8 (Step Over) kilka razy, aby dotrzeć do bloku try.

  2. Step into the division result = x / y.

    Wejdź w dzielenie result = x / y.

  3. Watch the "Console" tab — the debugger catches the ZeroDivisionError and shows you exactly where it happened!

    Obserwuj zakładkę "Console" — debugger łapie ZeroDivisionError i pokazuje dokładnie gdzie to się stało!

Expected behavior / Oczekiwane zachowanie:

  • Program pauses at breakpoint / Program zatrzymuje się na breakpoincie
  • Variables panel shows x=10, y=0 / Panel zmiennych pokazuje x=10, y=0
  • Stepping through shows execution flow / Przechodzenie krok po kroku pokazuje przepływ wykonania
  • Exception is caught and displayed in debugger / Wyjątek jest przechwycony i wyświetlony w debuggerze

🎯 Practice exercise / Ćwiczenie:

Try changing y = 0 to y = 2 and debug again. This time there will be no exception!

Spróbuj zmienić y = 0 na y = 2 i debuguj ponownie. Tym razem nie będzie wyjątku!


💡 6️⃣ Testy z pytest / Testing with pytest

Tests are small programs that check whether your code behaves correctly — like quality control on a production line.

Testy to krótkie programy, które sprawdzają, czy Twój kod działa tak, jak powinien — jak kontrola jakości na linii produkcyjnej.

They ensure that future changes don't break existing functionality.

Dzięki nim wiesz, że po zmianach nic się nie zepsuło.

📘 Documentation / Dokumentacja:

pytest Documentation

Read sections: "Get Started" and "How to write and report assertions" / Przeczytaj sekcje: "Get Started" i "How to write and report assertions"

🎥 Video / Wideo:

Corey Schafer – Pytest Tutorial (0:00–14:00)

Covers pytest basics and writing first tests / Omawia podstawy pytest i pisanie pierwszych testów

Why it matters / Dlaczego to ważne:

Tests act as safety nets — they catch bugs before users do.

Testy działają jak siatka bezpieczeństwa — wychwytują błędy zanim trafią do użytkowników.

🧩 Zadanie / Task:

Create a file test_main.py:

W pliku test_main.py:

def test_math():
    assert 2 + 2 == 4

def test_string():
    assert "hello".upper() == "HELLO"

Run the tests:

Uruchom testy:

uv run pytest

Expected output / Oczekiwany rezultat:

======================== test session starts ========================
collected 2 items

test_main.py ..                                              [100%]

======================== 2 passed in 0.01s =========================

💡 7️⃣ Docker – powtarzalne środowisko / Docker – Reproducible Environment

Docker lets you package your application into standardized containers — like shipping containers that ensure your cargo fits into repeatable, predictable units that work on any ship, train, or truck.

Docker pozwala zapakować aplikację w standaryzowane kontenery — jak kontenery transportowe, które zapewniają, że Twój ładunek mieści się w powtarzalnych, przewidywalnych jednostkach działających na każdym statku, pociągu czy ciężarówce.

That way your program behaves identically on every machine, regardless of local setup — the container specification guarantees consistency.

Dzięki temu Twój program działa identycznie na każdej maszynie, niezależnie od lokalnych ustawień — specyfikacja kontenera gwarantuje spójność.

📘 Documentation / Dokumentacja:

Docker Get Started

Read sections: "Overview" and "Part 1: Getting started" / Przeczytaj sekcje: "Overview" i "Part 1: Getting started"

🎥 Video / Wideo:

freeCodeCamp – Docker for Beginners (0:00–40:00)

Watch first 40 minutes covering Docker basics / Obejrzyj pierwsze 40 minut omawiające podstawy Dockera

Why it matters / Dlaczego to ważne:

With Docker, your project runs exactly the same on everyone's machine — no more "it works on my computer" problems.

Dzięki Dockerowi Twój projekt działa dokładnie tak samo u każdego — koniec z problemami "u mnie działa".

🧩 Zadanie / Task:

  1. Install Docker Desktop from the link above.

    Zainstaluj Docker Desktop z linku powyżej.

  2. Run a test container:

    Uruchom testowy kontener:

    docker run hello-world
  3. Notice that the program ran independently of your local installation.

    Zauważ, że program działał niezależnie od Twojej lokalnej instalacji.

Expected output / Oczekiwany rezultat:

Hello from Docker!
This message shows that your installation appears to be working correctly.
...

Check that Docker downloaded the image and ran it successfully.

Sprawdź, że Docker pobrał obraz i uruchomił go pomyślnie.


✅ Podsumowanie / Summary

Po tym bloku potrafisz / After this block you can:

  • uruchomić projekt w PyCharm,
  • instalować i aktualizować biblioteki przez uv,
  • używać Git i GitHub,
  • debugować i logować,
  • pisać testy pytest,
  • uruchomić kontener Docker.

📦 Bonus – Słowniczek / Glossary

Termin Znaczenie PL Meaning EN
IDE Zintegrowane środowisko programistyczne Integrated Development Environment
IntelliSense podpowiedzi składni code completion
Debugger narzędzie do śledzenia kodu krok po kroku step-by-step code tracer
Biblioteka / Package zestaw gotowych funkcji pre-written code bundle
Virtual Env (.venv) odizolowane środowisko projektu isolated project environment
Repository (Git) historia kodu code history
Container (Docker) zamknięte środowisko uruchomieniowe self-contained runtime environment