1. Project Overview & Quickstart (trekhleb/learn-python)
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.
- Help Ukraine via:
- More info on war.ukraine.ua and MFA of Ukraine
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:
- Find the topic you want to learn or recap.
- Read comments and/or documentation that is linked in each script's docstring (as in example above).
- Look at code examples and assertions to see usage examples and expected output.
- Change code or add new assertions to see how things work.
- Run tests and lint the code to see if it work and is
written correctly.
Table of Contents
- Getting Started
- Operators
- Arithmetic Operators (
+,-,*,/,//,%,**) - Bitwise Operators (
&,|,^,>>,<<,~) - Assignment Operators (
=,+=,-=,/=,//=etc.) - Comparison Operator (
==,!=,>,<,>=,<=) - Logical Operators (
and,or,not) - Identity Operators (
is,is not) - Membership Operators (
in,not in)
- Arithmetic Operators (
- Data Types
- Numbers (including booleans)
- Strings and their methods
- Lists and their methods (including list comprehensions)
- Tuples
- Sets and their methods
- Dictionaries
- Type Casting
- Control Flow
- The
ifstatement - The
forstatement (andrange()function) - The
whilestatement - The
trystatements - The
breakstatement - The
continuestatement
- The
- Functions
- Function Definition (
defandreturnstatements) - Scopes of Variables Inside Functions (
globalandnonlocalstatements) - Default Argument Values
- Keyword Arguments
- Arbitrary Argument Lists
- Unpacking Argument Lists (
*and**statements) - Lambda Expressions (
lambdastatement) - Documentation Strings
- Function Annotations
- Function Decorators
- Function Definition (
- Classes
- Modules
- Errors and Exceptions
- Handling Exceptions (
trystatement) - Raising Exceptions (
raisestatement)
- Handling Exceptions (
- Files
- Reading and Writing (
withstatement) - Methods of File Objects
- Reading and Writing (
- Additions
- The
passstatement - Generators (
yieldstatement)
- The
- Brief Tour of the Standard Libraries
- Serialization (
jsonlibrary) - File Wildcards (
globlibrary) - String Pattern Matching (
relibrary) - Mathematics (
math,random,statisticslibraries) - Dates and Times (
datetimelibrary) - Data Compression (
zliblibrary)
- Serialization (
- User input
- Terminal input (
inputstatement)
- Terminal 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 --versionNote 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.txtTesting 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:
pytestTo run specific tests please execute:
pytest ./path/to/the/test_file.pyLinting 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-docstringFlake8
To check if the code is written with respect
to PEP 8 style guide please run:
flake8 ./srcOr if you want to have more detailed output you may run:
flake8 ./src --statistics --show-source --countAuthor
File: README.es-ES.md
Playground y Cheatsheet para aprender Python
Esta es una colección de scripts de Python divididos en categorías que contienen
ejemplos de código con sus explicaciones, diferentes usos y links a recursos adicionales.
Lee esto en: Inglés, Portugués, Traditional Chinese, Українська.
Es un playground ya que puedes cambiar o añadir cosas al código para ver
cómo funciona y probarlo usando aserciones. También puedes
revisar el código que has escrito y averiguar si está acorde con
la guía de estilos de Python. Todo esto, en conjunto, puede hacer que tu proceso de aprendizaje
sea más interactivo y puede ayudarte a mantener la calidad del código muy alta desde el principio.
Es un cheatsheet porque puedes regresar y revisar los ejemplos de código para
fortalecer tus conocimientos sobre las sentencias y contrucciones estándar de Python.
Además, ya que el código tiene muchas aserciones, podrás ver el resultado de las funciones/sentencias en el mismo
código sin la necesidad de ejecutarlos.
También puede interesarte 🤖 Interactive Machine Learning Experiments
Cómo usar este repositorio
Cada script de Python en este repositorio sigue la estructura:
"""Lists <--- Nombre del tema
# @see: https://www.learnpython.org/en/Lists <-- Link a recurso adicional
Aquí puede haber una explicación detallada del tema en concreto (ej: información general sobre listas).
"""
def test_list_type():
"""Explicación del sub-tema.
Cada archivo contiene funciones de prueba que muestran sub-temas (ej: tipos de listas, métodos en listas).
"""
# Este es un ejemplo de cómo construir una lista. <-- Estos comentarios explican el procedimiento
squares = [1, 4, 9, 16, 25]
# Las listas pueden ser indexadas y cortadas.
# Al indexar devuelve el item.
assert squares[0] == 1 # <-- Estas aserciones muestran el resultado.
# Al cortar devuelve una nueva lista.
assert squares[-3:] == [9, 16, 25] # <-- Estas aserciones muestran el resultado.Normalmente, querrás hacer lo siguiente:
- Encontrar el tema que quieres aprender o revisar.
- Leer los comentarios y/o la documentación que está escrita en cada docstring del script (toma como ejemplo el script de arriba).
- Ver los ejemplos de código y las aserciones para conocer diferentes maneras de usar el código y entender el resultado previsto.
- Cambiar el código o añadir nuevas aserciones para ver cómo funcionan las cosas.
- Probar y revisar el código para ver si funciona y si está escrito
correctamente.
Contenido
- Empezando
- Operadores
- Operadores aritméticos (
+,-,*,/,//,%,**) - Operadores Bitwise (
&,|,^,>>,<<,~) - Operadores de atribución (
=,+=,-=,/=,//=etc.) - Operadores de comparación (
==,!=,>,<,>=,<=) - Operadores lógicos (
and,or,not) - Operadores de identidad (
is,is not) - Operadores de asociación (
in,not in)
- Operadores aritméticos (
- Tipos de datos
- Números (incluyendo booleans)
- Strings y sus métodos
- Listas y sus métodos (incluyendo comprensión de listas)
- Tuples
- Sets y sus métodos
- Diccionarios
- Tipo de casting
- Control de flujo
- La sentencia
if - La sentencia
for(y la funciónrange()) - La sentencia
while - La sentencia
try - La sentencia
break - La sentencia
continue
- La sentencia
- Funciones
- Definición de función (sentencias
defyreturn) - Ámbito de variables dentro de funciones (sentencias
globalynonlocal) - Valores de argumento predeterminados
- Argumentos de palabras clave
- Listas de argumento arbitrario
- Listas de argumentos en funciones (sentencias
*y**) - Expresiones Lambda (sentencia
lambda) - Strings de documentación
- Anotaciones en funciones
- Decoradores de funciones
- Definición de función (sentencias
- Clases
- Módulos
- Errores y excepciones
- Controlando excepciones (sentencia
try) - Generando excepciones (sentencia
raise)
- Controlando excepciones (sentencia
- Archivos
- Leyendo y escribiendo (sentencia
with) - Métodos de objetos de archivo
- Leyendo y escribiendo (sentencia
- Adicionales
- La sentencia
pass - Generadores (sentencia
yield)
- La sentencia
- Pequeño tour de las librerías estándar
- Serialización (librería
json) - Parámetros en archivos (librería
glob) - Expresiones regulares (librearía
re) - Matemática (librerías
math,randomystatistics) - Fechas y horas (librería
datetime) - Compresión de datos (librearía
zlib)
- Serialización (librería
Pre-requisitos
Instalando Python
Asegúrate de que tienes Python3 instalado en tu sistema.
Podrías utilizar la librería estándar venv para crear
entornos virtuales y tener Python, pip y todos los paquetes instalados en el directorio de tu
proyecto local para evitar cometer errores con paquetes del sistema y sus versiones.
Dependiendo de la instalación, tendrás acceso a Python3 ejecutando python o python3. Lo mismo
aplica para el administrador de paquetes pip - puedes tener acceso a él ejecutando pip o pip3.
Puedes ver tu versión actual de Python ejecutando:
python --versionTen en cuenta que cuando leas python en este repositorio, se asume que es Python 3.
Instalando dependencias
Instala todas las depencias requeridas para el proyecto ejecutando:
pip install -r requirements.txtProbando el código
Las pruebas son hechas usando el framework pytest.
Puedes añadir más pruebas por ti mismo añadiendo archivos y funciones con el prefijo test_
(ej: test_topic.py con la función def test_sub_topic() adentro).
Para ejecutar todas las pruebas, por favor escribe el siguiente comando desde el directorio
raíz del proyecto:
pytestPara ejecutar diferentes pruebas escribe:
pytest ./path/to/the/test_file.pyRevisando el código
La revisión del código está hecha usando las librerías pylint y flake8.
PyLint
Para revisar si el código sigue la guía de estilos
PEP 8, por favor ejecuta:
pylint ./src/En caso de que linter detecte un error (ej: missing-docstring), te recomiendo leer más sobre
el error concreto ejecutando:
pylint --help-msg=missing-docstringFlake8
Para revisar si el código sigue la guía de estilos
PEP 8, por favor ejecuta:
flake8 ./srcO, si quieres ver un output más detallado, ejecuta:
flake8 ./src --statistics --show-source --countApoya al proyecto
Puedes apoyar al proyecto a través de ❤️️ GitHub o ❤️️ Patreon.
File: README.pt-BR.md
Playground e Cheatsheet Para Aprender Python
Essa é uma coleção de scripts Python dividida em tópicos que contém
exemplos de código com explicações, diferentes usos e links para outras leituras.
Ler em: English, Español, Traditional Chinese, Українська.
É um playground porque você pode fazer alterações no código para ver como ele se comporta,
além de testá-lo usando asserções. Também é possível
revisar o código que você escreveu automaticamente e verificar se ele se encaixa
no guia de estilo de código Python.
Isso tudo pode tornar seu processo de aprendizagem mais interativo e ajudar a manter a qualidade
do código bastante alta desde o início.
É um cheatsheet porque você pode voltar a esses exemplos de código quando quiser recapitular a sintaxe das
estruturas padrão do Python. O código está cheio de asserções, então você poderá ver o retorno das funções sem precisar executá-las.
Você pode se interessar também por 🤖 Interactive Machine Learning Experiments
Como Usar Esse Repositório
Nesse repositório, cada script Python possui a seguinte estrutura:
"""Lists <--- Nome do tópico
# @see: https://www.learnpython.org/en/Lists <-- Link para outras leituras.
A seguir, uma explicação mais detalhada do tópico atual (ex, informações gerais sobre listas (Lists)).
"""
def test_list_type():
"""Explicação do subtópico.
Cada arquivo contém funções de teste que ilustram subtópicos (ou seja, tipo de lista, métodos de lista).
"""
# Here is an example of how to build a list. <-- Comentários em inglês explicam a ação.
squares = [1, 4, 9, 16, 25]
# Lists can be indexed and sliced.
# Indexing returns the item.
assert squares[0] == 1 # <-- As asserções ilustram o resultado.
# Slicing returns a new list.
assert squares[-3:] == [9, 16, 25] # <-- As asserções ilustram o resultado.Então você pode querer fazer o seguinte:
- Encontrar o tópico que deseja aprender ou recapitular.
- Ler os comentários e/ou a documentação vinculada em cada script (como no exemplo acima).
- Analisar os exemplos e asserções para ver exemplos de uso e saída esperada das funções.
- Alterar o código ou adicionar novas asserções para ver o que acontece.
- Executar testes e revisar o código para ver se ele
funciona e para saber se está escrito corretamente.
Índice
- Começando
- Operadores
- Operadores Aritméticos (
+,-,*,/,//,%,**) - Operadores Bitwise (
&,|,^,>>,<<,~) - Operadores de Atribuição (
=,+=,-=,/=,//=etc.) - Operadores de Comparação (
==,!=,>,<,>=,<=) - Operadores Lógicos (
and,or,not) - Operadores de Indentidade (
is,is not) - Operadores de Associação (
in,not in)
- Operadores Aritméticos (
- Tipos de Dados
- Números (incluindo boleanos)
- Strings e seus métodos
- Listas e seus métodos (incluindo lista de compreensões)
- Tuplas
- Conjuntos e seus métodos
- Dicionários
- Casting de Tipo
- Controles de Fluxo
- A declaração
if - A declaração
for(e a funçãorange()) - A declaração
while - A declaração
try - A declaração
break - A declaração
continue
- A declaração
- Funções
- Definição de Função (declaração
defereturn) - Variáveis Dentro das Funções (declaração
globalenonlocal) - Valores Padrão de Argumentos
- Argumentos de palavras-chave
- Listas de Argumento Arbitrárias
- Desfazendo Lista de Argumentos (declaração
*e**) - Expressões Lambda (declaração
lambda) - Documentação das Strings
- Função de Anotações
- Função de Decoradores
- Definição de Função (declaração
- Classes
- Módulos
- Erros e Exceções
- Tratando Exceções (declaração
try) - Levantando Exceções (declaração
raise)
- Tratando Exceções (declaração
- Arquivos
- Lendo e Escrevendo (declaração
with) - Métodos de Objetos de Arquivos
- Lendo e Escrevendo (declaração
- Adicional
- A declaração
pass - Geradores (declaração
yield)
- A declaração
- Algumas Bibliotecas Padrão
- Serialization (biblioteca
json) - File Wildcards (biblioteca
glob) - String Pattern Matching (biblioteca
re) - Matemática (bibliotecas
math,randomestatistics) - Tempo e Datas (biblioteca
datetime) - Comprimindo Dados (biblioteca
zlib)
- Serialization (biblioteca
Pré-requisitos
Instalando o Python
Certifique-se de ter o Python3 instalado em sua máquina.
Você pode usar a biblioteca padrão do Python venv
para criar ambientes virtuais e ter o Python, pip e todos os outros pacotes a serem instalados
a partir do diretório local do projeto para evitar mexer com pacotes externos ou do sistema.
Dependendo da sua instalação, você pode ter acesso ao interpretador Python3 executando python ou python3. O mesmo vale para o gerenciador de pacotes pip, você pode acessá-lo executando pip ou pip3.
Você pode ver a versão do seu Python executando:
python --versionObserve que neste repositório sempre que você vê o python, será assumido que é o Python 3.
Instalando dependências
Instale todas as dependências necessárias para o projeto executando:
pip install -r requirements.txtTestando o Código
Testes são feitos usando o framework pytest.
Você pode adicionar novos testes criando arquivos e funções com o prefixo test_
(ex. test_topic.py com a função def test_sub_topic() dentro).
Para executar todos os testes, execute o seguinte comando na pasta raiz do projeto:
pytestPara executar testes específicos, execute:
pytest ./path/to/the/test_file.pyRevisando o Código
A revisão é feita usando as bibliotecas pylint e flake8.
PyLint
Para verificar se o código está escrito de acordo com o guia de estilo
do PEP 8, execute:
pylint ./src/Caso o pylint detecte um erro (ex. missing-docstring), convém ler mais sobre erros específicos executando:
pylint --help-msg=missing-docstringFlake8
Para verificar se o código está escrito de acordo com o guia de estilo
do PEP 8, execute:
flake8 ./srcOu, se você quiser uma saída mais detalhada, execute:
flake8 ./src --statistics --show-source --countTraduzido por vilmacio22.
File: README.zh-TW.md
學習 Python 的練習場(Playground)和速查表(Cheatsheet)
此專案依據 目錄 分類收集了 Python 腳本,包含了程式碼範例及解釋、不同的使用情境以及衍伸閱讀連結。
閱讀英文原始版本: English, Português, Español, Українська.
此專案名稱之所以叫做 練習場(Playground),是因為您可以修改或是新增程式碼至範例中去觀察程式執行流程並使用斷言關鍵字(assert)來 測試程式。同時,此專案也使用了業界常用的工具來 檢查程式碼,確保您所撰寫的程式碼符合官方建議的 Python 程式碼風格規範。
總而言之,此專案會使您的學習過程更具互動性,並幫助您從一開始學習的時候就使用高品質的程式碼。
此專案名稱之所以也包含了 速查表(Cheatsheet) 是因為您可以隨時透過此專案中的 標準 Python 陳述式以及結構 回顧程式碼語法,也因為在此專案中的每個程式碼範例都使用了斷言來說明及教學,故您可以不用執行程式就看到函式/陳述式的預期輸出結果。
若對機器學習(Machine Learning)有興趣,可以參考專案原作者的另一個學習專案:🤖 Interactive Machine Learning Experiments
如何使用此專案儲存庫
在此專案儲存庫中的每一個 Python 腳本皆為以下結構:
"""串列(Lists) <--- 此為主題名稱
# @詳見: https://www.learnpython.org/en/Lists <-- 此為延伸閱讀連結
此處可能會有針對此主題更多的詳細說明(例如:關於串列的基本使用方法)
"""
def test_list_type():
"""此處為子主題解釋
每個檔案皆包含說明該子主題的測試函式(例如:串列型態、串列方法)
"""
# 建立串列之範例 <-- 此行是解釋下一行程式碼動作之註解
squares = [1, 4, 9, 16, 25]
# 串列可以被索引(indexed)及切片(sliced)
# 索引會回傳該索引位置之內容值
assert squares[0] == 1 # <-- 利用斷言來呈現結果
# 切片會回傳一個新的串列
assert squares[-3:] == [9, 16, 25] # <-- 利用斷言來呈現結果故您可以做以下動作:
- 找一個您想要學習或是回顧的 主題。
- 閱讀註解及/或包含於腳本文件字串(docstring)中的延伸閱讀資料(如上述之程式碼範例)。
- 查看程式碼範例並利用斷言來展示使用範例及預期輸出。
- 修改程式碼或新增新的斷言來了解程式運作流程。
- 執行測試 及 檢查程式碼 來確認程式是否被正確撰寫及是否可以被正確執行。
目錄
- 入門
- 運算子
- 資料類型
- 流程控制
- 函式
- 類別
- 模組
- 錯誤和例外
- 檔案
- 附加內容
- 標準函式庫簡介
使用此專案必備條件
安裝 Python
確認您已安裝 Python3 在您的電腦上。
您可能會想要使用標準 Python 函式庫所提供的 虛擬環境 功能在專案目錄中建立虛擬環境來佈署 Python 程式、pip 程式以及安裝所有需要的套件,藉此來避免作業系統中 Python 版本及相依性的混亂。
根據您的安裝方法,您可能可以通過以下方式執行 Python 3 直譯器:執行 python 或 python3 命令。pip 套件管理器執行方式也是如此:執行 pip 或 pip3。
您可以使用以下命令來確認 Python 版本:
python --version此專案儲存庫中的所有程式碼皆是基於 Python 3。
安裝相依性套件
透過以下命令安裝此專案需要的相依性套件:
pip install -r requirements.txt測試程式
此專案使用 pytest 測試框架來執行程式碼測試。
您可以新增以 test_ 為開頭的檔案/函式來新增測試。(例如:test_topic.py 檔案內有 def test_sub_topic() 測試函式)
請從專案根目錄下使用以下命令來執行所有測試:
pytest您也可以使用以下命令執行特定測試:
pytest ./path/to/the/test_file.py檢查程式碼
此專案使用 pylint 以及 flake8 函式庫來執行程式碼檢查。
PyLint
檢查撰寫之程式碼是否符合 PEP 8 風格規範,請執行以下命令:
pylint ./src/若此檢查工具偵測到錯誤(例如:missing-docstring),您可以使用以下命令查看特定錯誤之詳細說明:
pylint --help-msg=missing-docstringFlake8
檢查撰寫之程式碼是否符合 PEP 8 風格規範,請執行以下命令:
flake8 . /src若您希望得到更多詳細的輸出,您可以加上以下參數再執行此工具:
flake8 . /src --statistics --show-source --count支持此專案
您可以透過 ❤️️ GitHub 或 ❤️️ Patreon 支持原作者專案
2. Official Technical Reference & Guides (trekhleb/trekhleb.github.io)
trekhleb.dev
My personal website with a list of my projects that help people learn and blog posts about life, web-development, and machine-learning.
Development
The website is built on Gatsby. See the Gatsby cheat-sheet for development hints.
Running the project locally
Install proper version of Node:
nvm useInstall dependencies:
npm iTo run the project locally in development mode on http://localhost:8000:
npm run developView GraphiQL, an in-browser IDE, to explore your site's data and schema on http://localhost:8000/___graphql
To build the production version of the project:
npm run buildServe the production build for testing on http://localhost:9000:
npm run serveTo do ESLint and Type checking:
npm run lint
npm run typeTo fix the Lint errors run:
npm run lint -- --fixWorking with icons
Use react-icons.github.io to search for available icons.
Styling components
Use tailwindcss.com to search for available CSS classes.
Custom Domain Support
To serve the trekhleb.github.io web-site on a custom domain trekhleb.dev make sure that the public branch has CNAME file in the root folder. For more details read this.