Python Programming
Complete Learning Guide
From Basics to Production Deployment
Topics Covered: Python Syntax, Data Structures, Algorithms
Object-Oriented Programming, Advanced Topics
Data Science (NumPy, Pandas, Matplotlib)
Django Web Development
Production Deployment
Date: March 08, 2026
Total Pages: Comprehensive Guide
Page 1 of 16
Table of Contents
1. Python Syntax Fundamentals
2. Data Structures (Lists, Tuples, Dictionaries, Sets)
3. Algorithms (Searching, Sorting, Recursion)
4. Practical Projects
5. Object-Oriented Programming (OOP)
6. Advanced Python Topics
7. Data Science with Python
8. Django Web Development
9. Production Deployment Guide
Page 2 of 16
Part 1: Python Syntax Fundamentals
1.1 Variables and Data Types
Python uses dynamic typing, meaning you don't need to declare variable types explicitly. The
interpreter automatically determines the type based on the assigned value.
# Numbers
age = 25 # Integer
price = 19.99 # Float
complex_num = 3 + 4j # Complex number
# Strings
name = "Alice"
message = 'Hello World'
# Boolean
is_active = True
# None
result = None
1.2 Control Flow - Conditionals
Python uses if-elif-else statements for conditional logic. Indentation is crucial as it defines
code blocks.
age = 18
if age < 13:
print("Child")
elif age < 18:
print("Teenager")
else:
print("Adult")
1.3 Loops - For and While
# For loop
fruits = ['apple', 'banana', 'orange']
for fruit in fruits:
print(fruit)
# While loop
count = 0
while count < 5:
print(count)
count += 1
# Loop with range
for i in range(5):
print(i) # 0, 1, 2, 3, 4
1.4 Functions
def greet(name):
"""This is a docstring"""
return f"Hello, {name}!" Page 3 of 16
# Call function
result = greet("Alice")
# Function with default parameters
def greet_with_title(name, title="Mr."):
return f"Hello, {title} {name}"
# Multiple return values
def get_user_info():
name = "Alice"
age = 25
return name, age
user_name, user_age = get_user_info()
Page 4 of 16
Part 2: Data Structures
2.1 Lists - Ordered, Mutable Collections
Lists are the most versatile data structure in Python. They can hold mixed types and can be
modified after creation.
# Creating lists
fruits = ['apple', 'banana', 'orange']
numbers = [1, 2, 3, 4, 5]
mixed = [1, 'hello', 3.14, True]
# Accessing elements
print(fruits[0]) # 'apple'
print(fruits[-1]) # 'orange'
# Modifying lists
[Link]('grape')
[Link](1, 'kiwi')
[Link]('banana')
# List operations
print(len(numbers)) # 5
print(max(numbers)) # 5
print(sum(numbers)) # 15
# List comprehension
squares = [x**2 for x in range(10)]
2.2 Dictionaries - Key-Value Pairs
Dictionaries store data as key-value pairs, providing fast lookups and flexible data
organization.
student = {
'name': 'Alice',
'age': 20,
'grade': 'A',
'courses': ['Math', 'Physics']
}
# Accessing values
print(student['name'])
print([Link]('age'))
# Adding/Modifying
student['height'] = 165
student['age'] = 21
# Iterating
for key, value in [Link]():
print(f"{key}: {value}")
# Dictionary comprehension
squares = {x: x**2 for x in range(5)}
Page 5 of 16
Part 3: Algorithms
3.1 Understanding Big O Notation
Big O notation describes how an algorithm's performance scales with input size.
Understanding complexity helps you write efficient code.
Notation Name Example
O(1) Constant Accessing array element
O(log n) Logarithmic Binary search
O(n) Linear Linear search
O(n log n) Linearithmic Merge sort, Quick sort
O(n²) Quadratic Bubble sort, nested loops
3.2 Binary Search - O(log n)
def binary_search(arr, target):
"""Binary search on sorted array"""
left = 0
right = len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
# Test
sorted_numbers = [11, 12, 22, 25, 34, 64, 90]
result = binary_search(sorted_numbers, 25)
3.3 Quick Sort - O(n log n)
def quick_sort(arr):
"""Quick Sort algorithm"""
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
numbers = [64, 34, 25, 12, 22, 11, 90]
sorted_arr = quick_sort(numbers)
Page 6 of 16
Part 4: Object-Oriented Programming
4.1 The Four Pillars of OOP
Pillar Description
Encapsulation Bundle data and methods together, hide implementation details
Inheritance Create new classes from existing ones, code reuse
Polymorphism Same interface, different implementations
Abstraction Hide complexity, show only essentials
4.2 Class Example - E-Commerce System
class Product:
"""Base product class"""
def __init__(self, name, price, stock):
[Link] = name
self._price = price # Protected
[Link] = stock
@property
def price(self):
return self._price
@[Link]
def price(self, value):
if value < 0:
raise ValueError("Price cannot be negative!")
self._price = value
def is_available(self):
return [Link] > 0
class Book(Product):
"""Book inherits from Product"""
def __init__(self, name, price, stock, author, isbn):
super().__init__(name, price, stock)
[Link] = author
[Link] = isbn
def get_details(self):
return f"{[Link]} by {[Link]}"
Page 7 of 16
Part 5: Advanced Python Topics
5.1 Decorators
Decorators modify or enhance functions without changing their code. They're widely used in
frameworks like Django and Flask.
import time
def timer(func):
"""Measure function execution time"""
def wrapper(*args, **kwargs):
start = [Link]()
result = func(*args, **kwargs)
end = [Link]()
print(f"{func.__name__} took {end - start:.4f}s")
return result
return wrapper
@timer
def slow_function():
[Link](1)
return "Done!"
# Caching decorator
def memoize(func):
"""Cache function results"""
cache = {}
def wrapper(*args):
if args in cache:
return cache[args]
result = func(*args)
cache[args] = result
return result
return wrapper
5.2 Generators - Lazy Evaluation
def fibonacci_gen():
"""Generate Fibonacci sequence infinitely"""
a, b = 0, 1
while True:
yield a
a, b = b, a + b
fib = fibonacci_gen()
for _ in range(10):
print(next(fib)) # 0 1 1 2 3 5 8 13 21 34
# Generator expression (memory efficient)
squares = (x**2 for x in range(1000000))
Page 8 of 16
Part 6: Data Science with Python
6.1 NumPy - Numerical Computing
NumPy provides fast array operations, much faster than Python lists for numerical
computations.
import numpy as np
# Creating arrays
arr = [Link]([1, 2, 3, 4, 5])
matrix = [Link]([[1, 2, 3], [4, 5, 6]])
# Array operations
print(arr + 10) # [11 12 13 14 15]
print(arr * 2) # [2 4 6 8 10]
print(arr ** 2) # [1 4 9 16 25]
# Statistical operations
print([Link]()) # 3.0
print([Link]()) # 1.41
print([Link]()) # 15
# Boolean indexing
print(arr[arr > 2]) # [3 4 5]
6.2 Pandas - Data Manipulation
import pandas as pd
# Create DataFrame
data = {
'name': ['Alice', 'Bob', 'Charlie'],
'age': [25, 30, 35],
'salary': [75000, 85000, 95000]
}
df = [Link](data)
# Read CSV
df = pd.read_csv('[Link]')
# Data operations
print([Link]())
print([Link]())
print(df[df['age'] > 28])
# Group by
grouped = [Link]('department')['salary'].mean()
# Merge DataFrames
merged = [Link](df1, df2, on='employee_id')
Page 9 of 16
Part 7: Django Web Development
7.1 Django MTV Pattern
Django follows the Model-Template-View (MTV) pattern, similar to MVC but with different
terminology.
Component Purpose
Model Database layer - defines data structure
Template Presentation layer - HTML with Django template language
View Logic layer - processes requests and returns responses
7.2 Django Model Example
from [Link] import models
from [Link] import User
class Post([Link]):
STATUS_CHOICES = [
('draft', 'Draft'),
('published', 'Published'),
]
title = [Link](max_length=200)
slug = [Link](unique=True)
author = [Link](User, on_delete=[Link])
content = [Link]()
status = [Link](max_length=10, choices=STATUS_CHOICES)
created_at = [Link](auto_now_add=True)
published_at = [Link](default=[Link])
class Meta:
ordering = ['-published_at']
def __str__(self):
return [Link]
7.3 Django View Example
from [Link] import render, get_object_or_404
from .models import Post
def home(request):
"""Display all published posts"""
posts = [Link](status='published')
return render(request, 'blog/[Link]', {'posts': posts})
def post_detail(request, slug):
"""Display single post"""
post = get_object_or_404(Post, slug=slug)
[Link] += 1
[Link]()
return render(request, 'blog/post_detail.html', {'post': post})
Page 10 of 16
Part 8: Production Deployment
8.1 Deployment Checklist
✓ DEBUG = False in production settings
✓ SECRET_KEY stored in environment variables
✓ ALLOWED_HOSTS configured with domain names
✓ PostgreSQL database configured
✓ Static files collected and served (WhiteNoise)
✓ Media files storage configured
✓ Gunicorn installed as WSGI server
✓ Security settings enabled (SSL, CSRF, XSS protection)
✓ Environment variables in .env file
✓ [Link] created
✓ Database migrations applied
✓ Superuser created
✓ Error logging configured (Sentry)
✓ SSL certificate installed
✓ Backup strategy implemented
8.2 Production Settings
# settings/[Link]
import dj_database_url
from decouple import config
DEBUG = False
ALLOWED_HOSTS = config('ALLOWED_HOSTS').split(',')
# Database
DATABASES = {
'default': dj_database_url.config(
default=config('DATABASE_URL'),
conn_max_age=600
)
}
# Security
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_BROWSER_XSS_FILTER = True Page 11 of 16
SECURE_HSTS_SECONDS = 31536000
# Static files
STATIC_ROOT = BASE_DIR / 'staticfiles'
STATICFILES_STORAGE = '[Link]'
8.3 Heroku Deployment Files
# Procfile
web: gunicorn [Link]
# [Link]
python-3.11.5
# [Link]
Django==4.2.7
gunicorn==21.2.0
psycopg2-binary==2.9.9
whitenoise==6.6.0
dj-database-url==2.1.0
python-decouple==3.8
# Deploy commands
heroku create your-app-name
git push heroku main
heroku run python [Link] migrate
heroku run python [Link] createsuperuser
Page 12 of 16
Summary and Next Steps
What You've Learned
Python Fundamentals: Variables, data types, control flow, functions, and core syntax
Data Structures: Lists, tuples, dictionaries, sets, and when to use each
Algorithms: Searching (linear, binary), sorting (bubble, quick, merge), recursion, Big O
complexity
Object-Oriented Programming: Classes, inheritance, polymorphism, encapsulation,
abstraction
Advanced Topics: Decorators, generators, context managers, type hints, async
programming
Data Science: NumPy arrays, Pandas DataFrames, data cleaning, analysis, and visualization
Django Framework: Models, views, templates, forms, authentication, admin interface
Production Deployment: Environment configuration, database setup, security, static files,
deployment platforms
Recommended Next Steps
Build Projects: Create your own applications combining what you've learned
Contribute to Open Source: Find Python projects on GitHub and contribute
Learn Testing: Master pytest and test-driven development (TDD)
Explore Advanced Django: Django REST Framework, Celery for async tasks, Django
Channels
Advanced Data Science: Machine learning with scikit-learn, deep learning with
TensorFlow/PyTorch
Page 13 of 16
DevOps Skills: Docker, Kubernetes, CI/CD pipelines
Cloud Platforms: AWS, Google Cloud, Azure deployment and services
Keep Learning: Follow Python blogs, attend conferences, join communities
Page 14 of 16
Additional Resources
Official Documentation
• Python Documentation: [Link]
• Django Documentation: [Link]
• NumPy Documentation: [Link]
• Pandas Documentation: [Link]
• Matplotlib Documentation: [Link]
Learning Platforms
• Real Python: [Link]
• Python Official Tutorial: [Link]
• Django for Beginners: [Link]
• Kaggle (Data Science): [Link]
• Python Weekly Newsletter: [Link]
Community
• Python Reddit: r/Python, r/learnpython
• Stack Overflow: [Link]
• Python Discord Servers: Various active communities
• Local Python User Groups: Check [Link]
• PyCon Conferences: Annual Python conferences worldwide
Page 15 of 16
Congratulations!
You've completed a comprehensive journey through Python programming, from basic syntax
to production-ready web applications. This knowledge forms a solid foundation for your
software development career.
Remember: The key to mastery is practice. Build projects, solve problems, contribute to open
source, and never stop learning. The Python community is welcoming and supportive—don't
hesitate to ask questions and share your knowledge.
Happy Coding! ■
Page 16 of 16