Skip to content

Instantly share code, notes, and snippets.

@gbili
Last active August 22, 2024 18:34
Show Gist options
  • Save gbili/20240c209fd03c410faa860f261aec36 to your computer and use it in GitHub Desktop.
Save gbili/20240c209fd03c410faa860f261aec36 to your computer and use it in GitHub Desktop.
The little book of Python

Sure, let's work on a compact guide called The Little Book of Python, modeled after The Little Book of Deep Learning. The goal will be to provide a concise, yet comprehensive overview of Python, from basics to advanced topics, making it accessible but still dense with useful information. Here’s an outline to start with:


The Little Book of Python

Chapter 1: Why Python?

Python is a high-level, interpreted language known for its simplicity and readability. It’s favored in multiple domains like web development, data science, machine learning, automation, and more. Why Python?

  1. Easy to learn – Its syntax is straightforward, mimicking natural language.
  2. Versatile – From scripts to large systems, Python fits well in almost every software domain.
  3. Large ecosystem – Rich libraries and frameworks for almost anything: NumPy, pandas, TensorFlow, Django, Flask, etc.
  4. Community support – Massive support from developers and contributors worldwide.

Chapter 2: Python Basics

Hello, World!

print("Hello, World!")

This is the canonical entry into programming with Python.

Variables and Data Types

Python is dynamically typed, meaning variables are assigned without explicitly declaring their type.

x = 10       # integer
y = 3.14     # float
name = "Alice"  # string
is_true = True  # boolean

Basic Data Structures

Python provides several built-in data structures for storing collections of data.

Lists

my_list = [1, 2, 3, 4]

Tuples (Immutable)

my_tuple = (1, 2, 3)

Dictionaries (Hash Maps)

my_dict = {"key1": "value1", "key2": "value2"}

Sets (Unique elements)

my_set = {1, 2, 3, 3}

Chapter 3: Control Flow

Python uses indentation to define the structure of code blocks.

If-Else Statements

x = 5
if x > 3:
    print("x is greater than 3")
else:
    print("x is less than or equal to 3")

Loops

For Loop

for i in range(5):
    print(i)

While Loop

count = 0
while count < 5:
    print(count)
    count += 1

List Comprehensions (Pythonic!)

squares = [x ** 2 for x in range(10)]

Chapter 4: Functions and Modules

Defining Functions

Python functions are first-class objects, allowing them to be passed as arguments or returned from other functions.

def greet(name):
    return f"Hello, {name}!"

Default and Keyword Arguments

def add(a, b=5):
    return a + b

Lambda Expressions

Anonymous functions, often used for short, throwaway functions.

f = lambda x: x ** 2

Importing Modules

Python has a modular design. Code can be organized into separate files (modules) and packages.

import math
print(math.sqrt(16))

Chapter 5: Object-Oriented Programming (OOP)

Python supports OOP paradigms like classes, inheritance, and polymorphism.

Classes and Objects

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

    def bark(self):
        print(f"{self.name} says Woof!")

dog = Dog("Rex")
dog.bark()

Inheritance

class Animal:
    def __init__(self, species):
        self.species = species

class Cat(Animal):
    def meow(self):
        print("Meow")

cat = Cat("Feline")
cat.meow()

Chapter 6: Exceptions and Error Handling

Python uses try, except, finally blocks for exception handling.

try:
    1 / 0
except ZeroDivisionError as e:
    print("Cannot divide by zero")
finally:
    print("This will always run")

Custom Exceptions

class CustomError(Exception):
    pass

try:
    raise CustomError("Something went wrong!")
except CustomError as e:
    print(e)

Chapter 7: File I/O

Reading and writing files in Python is straightforward.

Reading Files

with open("file.txt", "r") as file:
    content = file.read()

Writing Files

with open("file.txt", "w") as file:
    file.write("Hello, file!")

Chapter 8: Libraries and Ecosystem

Python’s true power comes from its vast library ecosystem.

NumPy

import numpy as np
arr = np.array([1, 2, 3])
print(arr.mean())

Pandas

import pandas as pd
df = pd.DataFrame({"Name": ["Alice", "Bob"], "Age": [25, 30]})
print(df)

Matplotlib

import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 6])
plt.show()

Chapter 9: Functional Programming

Python has elements of functional programming.

Map, Filter, Reduce

nums = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, nums))

even = list(filter(lambda x: x % 2 == 0, nums))

from functools import reduce
total = reduce(lambda x, y: x + y, nums)

Closures

def outer(x):
    def inner(y):
        return x + y
    return inner

add_five = outer(5)
print(add_five(3))

Chapter 10: Concurrency and Parallelism

Python supports concurrency using threads and async features.

Multithreading

import threading

def print_numbers():
    for i in range(5):
        print(i)

t1 = threading.Thread(target=print_numbers)
t1.start()

AsyncIO

import asyncio

async def greet():
    print("Hello")
    await asyncio.sleep(1)
    print("World")

asyncio.run(greet())

Chapter 11: Best Practices

Virtual Environments

Use virtual environments to isolate dependencies.

python3 -m venv myenv
source myenv/bin/activate

Type Hinting

Though dynamically typed, Python supports optional type hints.

def add(a: int, b: int) -> int:
    return a + b

Code Formatting

Follow PEP 8 guidelines. Tools like black and flake8 enforce code standards.


Chapter 12: Testing

Unit Testing

Python comes with a built-in testing library: unittest.

import unittest

class TestMath(unittest.TestCase):
    def test_add(self):
        self.assertEqual(1 + 2, 3)

if __name__ == "__main__":
    unittest.main()

Pytest

Pytest is a more powerful and concise testing framework.

def test_add():
    assert 1 + 2 == 3

Chapter 13: Python for Data Science and Machine Learning

Python’s dominance in machine learning and data science is unquestionable.

Scikit-learn

from sklearn.linear_model import LinearRegression

model = LinearRegression()
model.fit([[1], [2], [3]], [1, 2, 3])

TensorFlow

import tensorflow as tf

model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=[1])])
model.compile(optimizer='sgd', loss='mean_squared_error')

Chapter 14: Advanced Topics

Decorators

A decorator modifies the behavior of a function or class.

def my_decorator(func):
    def wrapper():
        print("Something before the function")
        func()
        print("Something after the function")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()

Generators

Generators are functions that return an iterable set of items one at a time.

def my_gen():
    for i in range(5):
        yield i

for value in my_gen():
    print(value)

Context Managers

Context managers are used to manage resources like file streams.

with open("file.txt", "w") as file:
    file.write("Hello!")

Chapter 15: Conclusion

Python’s power lies in its simplicity and versatility. Whether you're building web applications, analyzing data, scripting tasks, or writing machine learning algorithms, Python is a tool that allows you to do it all.

What's next?

Explore deeper into any Python domain that suits your interest—web frameworks, data science, or automation. Python continues to grow, and so will your understanding as you keep learning.


That would be the basic structure of The Little Book of Python. It's intentionally minimal in some places, but provides just enough depth to make Python approachable while laying out the path forward for more advanced topics.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment