🐍 Python — Learn From Zero

Playground: Replit Python | Programiz — click, type, run.

What is Python?

Python is a high-level, readable programming language. It looks almost like English, so it's perfect for beginners. It's used for:

  • Web apps (Django, Flask, FastAPI)
  • Data science & AI (pandas, NumPy, PyTorch, TensorFlow)
  • Automation & scripts
  • Games, desktop apps, and more

Run Online — No Install

Open Replit, click Create Repl, choose Python, and start typing. Or use Programiz for quick snippets.

🟢 Beginner — Core Basics

Your First Program

python
print("Hello, world!")

print() writes text to the screen. Run it — you should see Hello, world!.

Variables & Types

A variable stores a value. Python figures out the type automatically.

python
name = "Ada"        # string (text)
age = 36            # integer (whole number)
height = 1.78       # float (decimal)
is_student = True   # boolean (True / False)

print(name, age, height, is_student)
Variable names: letters, numbers, underscores; can't start with a number. Use snake_case (lowercase with underscores).

If / Else — Making Decisions

python
age = 18
if age >= 18:
    print("You can vote!")
else:
    print("Too young to vote.")

Indentation (4 spaces) matters in Python — it defines blocks.

Loops — Repeat Yourself

For loop

python
for i in range(5):
    print(i)   # prints 0, 1, 2, 3, 4

While loop

python
n = 3
while n > 0:
    print(n)
    n -= 1
print("Blast off! 🚀")

Functions — Reusable Blocks

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

print(greet("World"))  # Hello, World!

def defines a function. return sends a value back.

Lists & Dictionaries

List (ordered collection)

python
fruits = ["apple", "banana", "cherry"]
fruits.append("date")
print(fruits[0])   # apple
print(len(fruits)) # 4

Dictionary (key → value)

python
person = {"name": "Ada", "age": 36, "lang": "Python"}
print(person["name"])
person["age"] = 37
print(person)

🟡 Intermediate — Building Real Programs

Modules & Packages

Split code into files. import brings in functionality.

python
# math_utils.py
def add(a, b):
    return a + b

# main.py
from math_utils import add
print(add(2, 3))  # 5

Standard library: random, math, datetime, json, os, pathlib.

File I/O

python
# Write
with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("Hello, file!\n")

# Read
with open("notes.txt", encoding="utf-8") as f:
    content = f.read()
print(content)

with auto-closes the file. Use encoding="utf-8" always.

Error Handling (try/except)

python
try:
    x = int(input("Number: "))
    print(10 / x)
except ValueError:
    print("That's not a number!")
except ZeroDivisionError:
    print("Can't divide by zero!")
else:
    print("Success!")
finally:
    print("Done.")

Comprehensions

Concise, pythonic one-liners for creating collections.

python
# List comprehension
squares = [x*x for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# Dict comprehension
name_len = {name: len(name) for name in ["Ada", "Grace", "Alan"]}
# {'Ada': 3, 'Grace': 5, 'Alan': 4}

# Set comprehension
unique_lens = {len(n) for n in ["Ada", "Grace", "Alan"]}
# {3, 4, 5}

Virtual Environments & pip

Isolate dependencies per project.

bash
# Create venv
python -m venv .venv

# Activate (Linux/Mac)
source .venv/bin/activate
# Activate (Windows PowerShell)
.venv\Scripts\Activate.ps1

# Install packages
pip install requests pandas

# Save requirements
pip freeze > requirements.txt

🔴 Advanced — Pro Python

Decorators

Functions that modify other functions.

python
import time
from functools import wraps

def timer(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        print(f"{func.__name__} took {time.perf_counter() - start:.4f}s")
        return result
    return wrapper

@timer
def slow_add(a, b):
    time.sleep(0.1)
    return a + b

print(slow_add(2, 3))

Generators & Iterators

Lazy evaluation — memory efficient for large data.

python
def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

fib = fibonacci()
for _ in range(10):
    print(next(fib))  # 0 1 1 2 3 5 8 13 21 34

Async / Await

Concurrent I/O without threads.

python
import asyncio
import aiohttp

async def fetch(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:
            return await resp.text()

async def main():
    urls = ["https://httpbin.org/get"] * 3
    results = await asyncio.gather(*[fetch(u) for u in urls])
    print(f"Fetched {len(results)} pages")

asyncio.run(main())

Type Hints (PEP 484+)

Optional static analysis for large codebases.

python
from typing import List, Dict

def greet_all(names: List[str]) -> Dict[str, str]:
    return {name: f"Hello, {name}!" for name in names}

print(greet_all(["Ada", "Grace"]))

Tools: mypy, pyright, VS Code + Pylance.

What's Next?

  • Build a tiny project: Guess the Number, To-Do List, Weather CLI
  • Explore data science with pandas, polars, matplotlib
  • Try web with FastAPI or Django
  • Learn testing with pytest

Practice daily for 20 minutes. Consistency > intensity.