← Back to Blog

Notes on Learning Python

2026-03-24·3 min read
PythonBeginnerIntermediateAdvancedCheatsheet

Why Python?

Python is simple, readable, and versatile. It powers web apps, data science, ML/AI, automation, and APIs — with a massive standard library and 400k+ packages on PyPI.

Setup & Hello World

# Verify install
python --version
 
# Virtual environment
python -m venv .venv
source .venv/bin/activate   # Mac/Linux
 
# Install packages
pip install requests numpy pandas
# hello.py
print("Hello, World!")
name = input("Your name: ")
print(f"Hello, {name}!")

Basics

Variables & Types

name    = "Alice"         # str
age     = 30              # int
height  = 5.7             # float
active  = True            # bool
nothing = None            # NoneType
 
# Type hints (Python 3.5+) — optional but recommended
score: int = 100
label: str = "win"

Strings

name = "Alice"
print(f"Hello {name}, you are {2024 - 1994} years old")
 
s = "  Hello World  "
s.strip()           # "Hello World"
s.lower()           # "  hello world  "
s.replace("World", "Python")
s.split()           # ["Hello", "World"]
", ".join(["a","b","c"])  # "a, b, c"

Control Flow

score = 85
 
if score >= 90:
    print("A")
elif score >= 80:
    print("B")
else:
    print("C")
 
# Ternary
label = "pass" if score >= 60 else "fail"

Functions

def greet(name: str, greeting: str = "Hello") -> str:
    return f"{greeting}, {name}!"
 
greet("Alice")            # "Hello, Alice!"
greet("Alice", "Hi")      # "Hi, Alice!"
 
# *args and **kwargs
def total(*args):
    return sum(args)
 
# Lambda
square = lambda x: x ** 2
 
# List comprehension
squares = [x**2 for x in range(10)]
even_sq = [x**2 for x in range(10) if x % 2 == 0]

Data Types Cheatsheet

TypeExampleMutableKey Methods
str"hello"No.upper() .split() .strip()
int42NoArbitrary precision
list[1, 2, 3]Yes.append() .pop() .sort()
dict{"k": "v"}Yes.get() .keys() .items()
set{1, 2, 3}Yes.add() .union()
tuple(1, 2, 3)NoUnpack: a, b = (1, 2)

OOP

class Animal:
    def __init__(self, name: str, sound: str):
        self.name = name
        self._sound = sound
 
    def speak(self) -> str:
        return f"{self.name} says {self._sound}"
 
class Dog(Animal):
    def __init__(self, name):
        super().__init__(name, "Woof")
 
# Dataclass
from dataclasses import dataclass
 
@dataclass
class Point:
    x: float
    y: float
    label: str = "point"

Advanced Concepts

Decorators

import functools, time
 
def timer(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        t = time.time()
        result = func(*args, **kwargs)
        print(f"{time.time()-t:.4f}s")
        return result
    return wrapper

async / await

import asyncio
 
async def fetch(url: str) -> str:
    await asyncio.sleep(1)
    return f"data from {url}"
 
async def main():
    results = await asyncio.gather(
        fetch("url1"),
        fetch("url2"),
    )
 
asyncio.run(main())

Error Handling

try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Error: {e}")
except (TypeError, ValueError) as e:
    print(f"Type or value error: {e}")
else:
    print("No error!")
finally:
    print("Always runs")

Do's & Don'ts

DO:

  • Use f-strings for string formatting
  • Use type hints for clarity and IDE support
  • Use with for file and resource handling
  • Use is None not == None
  • Write tests with pytest

DON'T:

  • Don't use mutable defaults: def f(x=[]): — use None
  • Don't catch bare except: — always specify the exception
  • Don't modify a list while iterating over it