learn-python README

The project's README from github.com/trekhleb/learn-python. As one markdown file: README.md.

Playground and Cheatsheet for Learning Python

🇺🇦 UKRAINE IS BEING ATTACKED BY RUSSIAN ARMY. CIVILIANS ARE GETTING KILLED. RESIDENTIAL AREAS ARE GETTING BOMBED.


Build Status

This is a collection of Python scripts that are split by topics and contain code examples with explanations, different use cases and links to further readings.

Read this in: Português, Español, Traditional Chinese, Українська.

It is a playground because you may change or add the code to see how it works and test it out using assertions. It also allows you to lint the code you've wrote and check if it fits to Python code style guide. Altogether it might make your learning process to be more interactive and it might help you to keep code quality pretty high from very beginning.

It is a cheatsheet because you may get back to these code examples once you want to recap the syntax of standard Python statements and constructions. Also because the code is full of assertions you'll be able to see expected functions/statements output right away without launching them.

You might also be interested in 🤖 Interactive Machine Learning Experiments

How to Use This Repository

Each Python script in this repository has the following structure:

"""Lists  <--- Name of the topic here

# @see: https://www.learnpython.org/en/Lists  <-- Link to further readings goes here

Here might go more detailed explanation of the current topic (i.e. general info about Lists).
"""


def test_list_type():
    """Explanation of sub-topic goes here.
    
    Each file contains test functions that illustrate sub-topics (i.e. lists type, lists methods).
    """
    
    # Here is an example of how to build a list.  <-- Comments here explain the action
    squares = [1, 4, 9, 16, 25]
    
    # Lists can be indexed and sliced. 
    # Indexing returns the item.
    assert squares[0] == 1  # <-- Assertions here illustrate the result.
    # Slicing returns a new list.
    assert squares[-3:] == [9, 16, 25]  # <-- Assertions here illustrate the result.

So normally you might want to do the following:

Table of Contents

  1. Getting Started
  2. Operators
  3. Data Types
  4. Control Flow
  5. Functions
  6. Classes
  7. Modules
  8. Errors and Exceptions
  9. Files
  10. Additions
  11. Brief Tour of the Standard Libraries
  12. User input

Prerequisites

Installing Python

Make sure that you have Python3 installed on your machine.

You might want to use venv standard Python library to create virtual environments and have Python, pip and all dependent packages to be installed and served from the local project directory to avoid messing with system wide packages and their versions.

Depending on your installation you might have access to Python3 interpreter either by running python or python3. The same goes for pip package manager - it may be accessible either by running pip or pip3.

You may check your Python version by running:

python --version

Note that in this repository whenever you see python it will be assumed that it is Python 3.

Installing dependencies

Install all dependencies that are required for the project by running:

pip install -r requirements.txt

Testing the Code

Tests are made using pytest framework.

You may add new tests for yourself by adding files and functions with test_ prefix (i.e. test_topic.py with def test_sub_topic() function inside).

To run all the tests please execute the following command from the project root folder:

pytest

To run specific tests please execute:

pytest ./path/to/the/test_file.py

Linting the Code

Linting is done using pylint and flake8 libraries.

PyLint

To check if the code is written with respect to PEP 8 style guide please run:

pylint ./src/

In case if linter will detect error (i.e. missing-docstring) you may want to read more about specific error by running:

pylint --help-msg=missing-docstring

More about PyLint

Flake8

To check if the code is written with respect to PEP 8 style guide please run:

flake8 ./src

Or if you want to have more detailed output you may run:

flake8 ./src --statistics --show-source --count

More about Flake8

Author

learn-python (trekhleb/learn-python)

Searching Database…

Что это такое?Набор Python-скриптов, разбитых по темам: в каждом — примеры кода с пояснениями. Это одновременно и песочница, где можно менять код и проверять себя через ассерты, и шпаргалка, чтобы быстро освежить синтаксис Python.
Это пакет на Python, который я устанавливаю, или репозиторий, который я клонирую и читаю?Это репозиторий, который вы клонируете и в котором работаете, а не устанавливаемая библиотека или приложение. Скрипты читаются и правятся напрямую — в README прямо предлагается менять код и добавлять свои примеры.
Как это запустить?Склонируйте репозиторий, убедитесь, что Python 3 есть на компьютере (интерпретатор может называться python или python3), создайте виртуальное окружение и установите зависимости проекта через pip.
Нужно ли что-то ещё, кроме самого Python?Только Python 3 — всё остальное pip подтянет одной командой. В README советуют использовать venv, чтобы Python, pip и пакеты жили в папке проекта, а не засоряли системные.
Здесь только базовый Python или ещё фреймворки и машинное обучение?Только базовый язык: двенадцать разделов — от синтаксиса и операторов до классов, файлов, генераторов и краткого обзора стандартных библиотек вроде json, re и datetime. Никаких фреймворков и машинного обучения здесь нет.
Это для полных новичков или для тех, кто уже пишет на Python?И для тех, и для других. Новички могут проходить темы шаг за шагом, читая комментарии и ссылки на документацию, а кто уже пишет на Python — может сразу открыть нужный раздел и освежить синтаксис.
Имеет ли значение, работаю я на Windows, macOS или Linux?Нет — это обычные скрипты на Python 3, проверяемые через pytest, поэтому они работают в любой ОС, где установлен Python 3.
Как выглядит один из скриптов изнутри?Все скрипты устроены одинаково: сначала docstring с пояснениями и ссылками на дополнительную документацию, затем примеры кода с комментариями, которые можно запускать, менять и расширять.
Обязательно ли запускать каждый скрипт, чтобы понять, что он делает?Нет — скрипты полны ассертов, так что ожидаемый результат функций и инструкций виден прямо в коде, ничего запускать не нужно.
Как проверить, что мои правки работают?Добавьте файлы и функции с префиксом test (например, файл testtopic.py с функцией def testsubtopic() внутри) и запустите pytest из корня проекта — все тесты сразу или только нужные. Pylint и flake8 проверят, что код соответствует стилю PEP 8.
README есть на других языках?Да — кроме английского есть версии на португальском, испанском, китайском (традиционном) и украинском.
Creator
trekhleb
Size
<0.1 MB
Stars
18.4K
Updated
CommitApr 06
Age
8y
Commits · 90 Days