Convert Figma logo to code with AI

trekhleb logolearn-python

📚 Playground and cheatsheet for learning Python. Collection of Python scripts that are split by topics and contain code examples with explanations.

17,033
2,796
17,033
35

Top Related Projects

Learn how to design large-scale systems. Prep for the system design interview. Includes Anki flashcards.

199,949

All Algorithms implemented in Python

An opinionated list of awesome Python frameworks, libraries, software and resources.

Python - 100天从新手到大师

Minimal examples of data structures and algorithms in Python

A collection of design patterns/idioms in Python

Quick Overview

"learn-python" is a GitHub repository created by Oleksii Trekhleb that serves as a comprehensive resource for learning Python programming. It contains a collection of Python scripts covering various topics, from basic syntax to advanced concepts, along with explanations and examples.

Pros

  • Covers a wide range of Python topics, from beginner to advanced levels
  • Well-organized structure with clear explanations and code examples
  • Regularly updated with new content and improvements
  • Free and open-source, accessible to anyone interested in learning Python

Cons

  • May be overwhelming for absolute beginners due to the vast amount of information
  • Lacks interactive exercises or quizzes for hands-on practice
  • Some advanced topics might require additional resources for in-depth understanding

Code Examples

This repository is not a code library but a collection of Python scripts and explanations. Therefore, code examples are not applicable in the context of using it as a library.

Getting Started

To get started with the "learn-python" repository:

  1. Clone the repository:

    git clone https://github.com/trekhleb/learn-python.git
    
  2. Navigate to the cloned directory:

    cd learn-python
    
  3. Browse the folders and files to explore different Python topics.

  4. Open the Python scripts in your preferred text editor or IDE to study the code and explanations.

  5. Run individual scripts to see the output and experiment with the code:

    python3 path/to/script.py
    

Remember to have Python installed on your system before running the scripts. The repository is designed for learning purposes, so feel free to modify and experiment with the code as you progress through the topics.

Competitor Comparisons

Learn how to design large-scale systems. Prep for the system design interview. Includes Anki flashcards.

Pros of system-design-primer

  • Comprehensive coverage of system design concepts and principles
  • Includes real-world examples and case studies from large-scale systems
  • Provides visual aids and diagrams to illustrate complex concepts

Cons of system-design-primer

  • Focuses primarily on system design, not Python programming specifically
  • May be overwhelming for beginners due to its depth and breadth
  • Less hands-on coding practice compared to learn-python

Code comparison

system-design-primer:

# Example: Consistent hashing
def get_server(key):
    hash = md5(key).digest()
    return bisect(circle, hash)

learn-python:

# Example: Basic data structures
fruits = ['apple', 'banana', 'cherry']
fruits.append('date')
print(fruits)

The system-design-primer repository provides a comprehensive guide to system design concepts, making it ideal for software engineers preparing for system design interviews or looking to improve their understanding of large-scale systems. It offers in-depth explanations, visual aids, and real-world examples.

On the other hand, learn-python is more focused on teaching Python programming fundamentals through practical examples and exercises. It provides a structured approach to learning Python, making it more suitable for beginners or those looking to improve their Python skills specifically.

While system-design-primer may include some Python code examples, they are typically more complex and focused on system design concepts. learn-python offers more straightforward, beginner-friendly code examples that cover Python basics and common programming tasks.

199,949

All Algorithms implemented in Python

Pros of Python

  • Extensive collection of algorithms implemented in Python
  • Well-organized directory structure by algorithm type
  • Active community with frequent contributions and updates

Cons of Python

  • Less focus on beginner-friendly explanations and tutorials
  • May lack comprehensive documentation for each algorithm
  • Potentially overwhelming for newcomers due to its vast scope

Code Comparison

learn-python:

def binary_search(array, target):
    left, right = 0, len(array) - 1
    while left <= right:
        mid = (left + right) // 2
        if array[mid] == target:
            return mid
        elif array[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1

Python:

def binary_search(arr, x):
    low = 0
    high = len(arr) - 1
    mid = 0
    while low <= high:
        mid = (high + low) // 2
        if arr[mid] < x:
            low = mid + 1
        elif arr[mid] > x:
            high = mid - 1
        else:
            return mid
    return -1

Both repositories offer valuable resources for learning Python and algorithms. learn-python provides a more structured learning path with explanations and examples, making it ideal for beginners. Python offers a comprehensive collection of algorithm implementations, suitable for those looking to explore various algorithmic solutions in Python. The code comparison shows similar implementations of binary search, with minor differences in variable naming and structure.

An opinionated list of awesome Python frameworks, libraries, software and resources.

Pros of awesome-python

  • Comprehensive collection of Python resources, libraries, and tools
  • Well-organized into categories for easy navigation
  • Regularly updated with community contributions

Cons of awesome-python

  • Lacks structured learning path for beginners
  • No code examples or explanations for listed resources
  • May be overwhelming for newcomers due to the sheer volume of information

Code comparison

learn-python:

def binary_search(array, target):
    left, right = 0, len(array) - 1
    while left <= right:
        mid = (left + right) // 2
        if array[mid] == target:
            return mid
        elif array[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1

awesome-python:

No direct code examples are provided in the repository. It primarily serves as a curated list of Python resources and libraries.

Summary

learn-python is focused on providing a structured learning path with code examples and explanations, making it ideal for beginners and those looking to improve their Python skills. awesome-python, on the other hand, serves as a comprehensive reference for Python resources, libraries, and tools, making it valuable for developers of all levels seeking specific solutions or exploring the Python ecosystem.

Python - 100天从新手到大师

Pros of Python-100-Days

  • Comprehensive curriculum covering 100 days of Python learning
  • Includes practical projects and real-world applications
  • Structured daily lessons for consistent progress

Cons of Python-100-Days

  • May be overwhelming for absolute beginners
  • Less focus on algorithmic problem-solving compared to learn-python
  • Some content may be outdated due to the repository's age

Code Comparison

Python-100-Days:

def bubble_sort(items):
    for i in range(len(items) - 1):
        for j in range(len(items) - 1 - i):
            if items[j] > items[j + 1]:
                items[j], items[j + 1] = items[j + 1], items[j]

learn-python:

def bubble_sort(array):
    n = len(array)
    for i in range(n):
        for j in range(0, n - i - 1):
            if array[j] > array[j + 1]:
                array[j], array[j + 1] = array[j + 1], array[j]

Both repositories provide similar implementations of the bubble sort algorithm, with minor differences in variable naming and loop structure. learn-python's version is slightly more optimized by reducing the number of comparisons in each pass.

Minimal examples of data structures and algorithms in Python

Pros of algorithms

  • Focuses specifically on algorithms and data structures
  • Includes implementations in multiple languages (Python, C++, JavaScript)
  • Provides more advanced topics like graph algorithms and machine learning

Cons of algorithms

  • Less beginner-friendly, assumes more prior programming knowledge
  • Lacks comprehensive explanations and tutorials for each topic
  • Not as well-organized or structured as learn-python

Code Comparison

algorithms (Python implementation of binary search):

def binary_search(list, item):
    low = 0
    high = len(list) - 1
    while low <= high:
        mid = (low + high) // 2
        guess = list[mid]
        if guess == item:
            return mid
        if guess > item:
            high = mid - 1
        else:
            low = mid + 1
    return None

learn-python (Python implementation of binary search):

def binary_search(array, target):
    left, right = 0, len(array) - 1
    while left <= right:
        middle = (left + right) // 2
        if array[middle] == target:
            return middle
        elif array[middle] < target:
            left = middle + 1
        else:
            right = middle - 1
    return -1

Both repositories provide similar implementations of binary search, demonstrating the algorithm's core concepts. However, learn-python generally offers more detailed explanations and a wider range of Python-specific topics, making it more suitable for beginners learning Python programming.

A collection of design patterns/idioms in Python

Pros of python-patterns

  • Focuses specifically on design patterns, providing in-depth explanations and implementations
  • Includes a wide variety of patterns, categorized by type (creational, structural, behavioral)
  • Offers real-world examples and use cases for each pattern

Cons of python-patterns

  • Less beginner-friendly, assumes prior Python knowledge
  • Narrower scope, limited to design patterns rather than general Python learning
  • May not cover basic Python concepts and syntax

Code Comparison

python-patterns (Factory Method pattern):

class Dog:
    def __init__(self, name):
        self._name = name

    def speak(self):
        return "Woof!"

class Cat:
    def __init__(self, name):
        self._name = name

    def speak(self):
        return "Meow!"

learn-python (Basic class example):

class Animal:
    def __init__(self, name, sound):
        self.name = name
        self.sound = sound

    def make_sound(self):
        print(f"{self.name} says {self.sound}")

dog = Animal("Dog", "Woof")
dog.make_sound()

The python-patterns example demonstrates a specific design pattern (Factory Method), while learn-python focuses on basic class structure and usage.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

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:

  • 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

  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