Learning Python Programming

Python is the most popular beginner language and a powerhouse for web, data science, automation, and more. Learn the essentials and build real projects as you go.

Progress: 0% (0/0 sections)

Why Learn Python?

  • Beginner-friendly: Simple, readable syntax with no boilerplate
  • Versatile: Used for web, data science, scripting, automation, and more
  • Massive ecosystem: Thousands of libraries for every task
  • Data science leader: The go-to language for AI, ML, and analytics

Python vs Other Languages

Feature Python C JavaScript Java
Typing Dynamic Static Dynamic Static
Performance Moderate High Moderate High
Learning Curve Gentle Steep Gentle Moderate
Best For Web, Data, Scripting Systems, Embedded Web, Apps Enterprise, Android

Your Learning Path

Follow this structured progression to master Python. Each step builds on the previous one.

Basics
2 hours
Control Flow
2 hours
Functions & Modules
3 hours
Lists, Dicts, Sets
3 hours
Classes & OOP
4 hours
File I/O & Exceptions
2 hours
Decorators & Context Managers
3 hours
Async/Await
4 hours

Interactive Lessons

Click each lesson to expand and learn. Try the code examples locally or in your preferred online editor (e.g., Replit) to experiment and understand how Python works.

Variables, Types & Basic Operations

Python uses dynamic typing, so you don't need to declare variable types. The type is inferred at runtime. This makes Python flexible and easy to use for beginners.

Built-in Types

  • int - Integer numbers (e.g., 42)
  • float - Decimal numbers (e.g., 3.14)
  • str - Text strings (e.g., "hello")
  • bool - Boolean values (True, False)

Variable Assignment

x = 10
name = "Alice"
price = 19.99
is_valid = True

Type Conversion

x = 5
s = str(x)      # '5'
y = float(x)    # 5.0
b = bool(x)     # True

String Formatting

name = "Bob"
age = 30
print(f"Hello, {name}. You are {age} years old.")

Check Types

print(type(42))        # 
print(type("hi"))     # 

Key Takeaway: Python variables are easy to use and flexible. You can reassign variables to different types, but be careful with type errors in larger programs.

Lists & Dictionaries

Lists and dictionaries are the most commonly used data structures in Python. Lists are ordered, mutable sequences. Dictionaries are key-value stores.

List Basics

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

List Comprehensions

squares = [x*x for x in range(5)]
print(squares)  # [0, 1, 4, 9, 16]

Dictionary Basics

person = {"name": "Alice", "age": 25}
print(person["name"])
person["city"] = "NYC"
for key, value in person.items():
    print(key, value)

Nested Structures

users = [
    {"name": "Bob", "age": 30},
    {"name": "Carol", "age": 27}
]
print(users[1]["name"])

Common Mistake: Shallow vs Deep Copy

import copy
list1 = [[1, 2], [3, 4]]
list2 = list1.copy()      # Shallow copy
list3 = copy.deepcopy(list1)  # Deep copy
list1[0][0] = 99
print(list2)  # [[99, 2], [3, 4]]
print(list3)  # [[1, 2], [3, 4]]

Key Takeaway: Lists and dictionaries are flexible and powerful, but be careful with copying nested structures.

Control Flow & Loops

Python provides intuitive control flow with if/elif/else and powerful loops with for and while.

# If/elif/else
age = 20
if age >= 18:
    print("Adult")
elif age >= 13:
    print("Teenager")
else:
    print("Child")

# For loops with range
for i in range(5):
    print(i)  # 0, 1, 2, 3, 4

# For loops with lists
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# While loops
count = 0
while count < 3:
    print(f"Count: {count}")
    count += 1

# Break and continue
for i in range(10):
    if i == 3:
        continue  # Skip 3
    if i == 7:
        break  # Stop at 7
    print(i)
Functions & Modules

Functions organize code into reusable blocks. Modules let you organize functions across files.

# Function definition
def greet(name):
    """Docstring: This function greets someone."""
    return f"Hello, {name}!"

# Call function
message = greet("Alice")
print(message)

# Default arguments
def power(base, exponent=2):
    return base ** exponent

print(power(3))      # 9 (uses default)
print(power(3, 3))   # 27

# Variable arguments
def sum_all(*numbers):
    return sum(numbers)

print(sum_all(1, 2, 3, 4))  # 10

# Importing modules
import math
print(math.sqrt(16))  # 4.0

from datetime import datetime
print(datetime.now())
Classes & OOP

Classes bundle data and functions together. Python supports full object-oriented programming.

# Class definition
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def greet(self):
        return f"Hi, I'm {self.name}"
    
    def __str__(self):
        return f"Person({self.name}, {self.age})"

# Create instance
person = Person("Alice", 30)
print(person.greet())
print(person)  # Uses __str__

# Inheritance
class Student(Person):
    def __init__(self, name, age, grade):
        super().__init__(name, age)
        self.grade = grade
    
    def study(self):
        return f"{self.name} is studying"

student = Student("Bob", 16, "10th")
print(student.greet())   # Inherited
print(student.study())    # New method
File I/O & Exceptions

Python makes file handling easy with context managers. Exceptions handle errors gracefully.

# Writing to a file
with open('data.txt', 'w') as f:
    f.write("Hello\n")
    f.write("World\n")

# Reading from a file
with open('data.txt', 'r') as f:
    content = f.read()
    print(content)

# Reading lines
with open('data.txt', 'r') as f:
    for line in f:
        print(line.strip())

# Exception handling
try:
    number = int(input("Enter a number: "))
    result = 10 / number
    print(f"Result: {result}")
except ValueError:
    print("Invalid number")
except ZeroDivisionError:
    print("Cannot divide by zero")
except Exception as e:
    print(f"Error: {e}")
finally:
    print("Cleanup code runs always")
Decorators

Decorators modify or enhance functions. They use the @ syntax and are powerful for cross-cutting concerns.

import time
from functools import wraps

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

@timer
def slow_function():
    time.sleep(1)
    return "Done"

result = slow_function()

# Decorator with arguments
def repeat(times):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            for _ in range(times):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

@repeat(3)
def say_hello():
    print("Hello!")

say_hello()  # Prints "Hello!" 3 times
Async Programming

Async programming enables concurrent operations without threads. Python's asyncio makes it elegant.

import asyncio

# Async function (coroutine)
async def fetch_data(name, delay):
    print(f"Fetching {name}...")
    await asyncio.sleep(delay)  # Non-blocking wait
    print(f"Done fetching {name}")
    return f"Data from {name}"

# Running async functions
async def main():
    # Run sequentially
    result1 = await fetch_data("API 1", 1)
    result2 = await fetch_data("API 2", 1)
    
    # Run concurrently
    results = await asyncio.gather(
        fetch_data("API 3", 1),
        fetch_data("API 4", 1),
        fetch_data("API 5", 1)
    )
    print(results)

# Run the event loop
asyncio.run(main())

# Async with timeout
async def with_timeout():
    try:
        await asyncio.wait_for(fetch_data("Slow", 5), timeout=2)
    except asyncio.TimeoutError:
        print("Operation timed out")

Curated GitHub Repositories

Explore hand-picked repositories to accelerate your Python learning. Filter by category or search by name and topics.

Loading repositories...

Practice Projects

The best way to learn Python is by building. These projects progressively build your skills:

  • 1. CLI Todo App
    2-3 hours Beginner

    Build a command-line todo list application. Add, remove, and list tasks. Save tasks to a file.

    Key Concepts: input(), lists, file I/O, functions
    View Starter Code
    tasks = []
    
    while True:
        cmd = input("Enter command (add/list/quit): ")
        if cmd == "add":
            task = input("Task: ")
            tasks.append(task)
        elif cmd == "list":
            for i, t in enumerate(tasks):
                print(f"{i+1}. {t}")
        elif cmd == "quit":
            break
    
  • 2. Web Scraper with BeautifulSoup
    4-5 hours Intermediate

    Write a script to fetch a web page and extract information using BeautifulSoup. Save results to CSV.

    Key Concepts: requests, BeautifulSoup, CSV, for loops
  • 3. Flask REST API
    6-8 hours Intermediate

    Create a RESTful API using Flask. Implement CRUD operations for a resource (e.g., notes).

    Key Concepts: Flask, routes, JSON, HTTP methods
  • 4. Data Analysis with Pandas
    5-6 hours Intermediate

    Analyze a CSV dataset using pandas. Calculate statistics, filter data, and plot results.

    Key Concepts: pandas, DataFrame, matplotlib, data cleaning
  • 5. Discord Bot
    8-10 hours Advanced

    Build a Discord bot using discord.py. Respond to commands, manage roles, and interact with users.

    Key Concepts: discord.py, async, events, APIs

Resources Hub

Your Progress

Check off lessons as you complete them. Your progress is saved locally in your browser.