Python Complete Tutorial: Beginner to Advanced (95 Topics with Code) — a practical guide to Python complete tutorial with clear examples you can reuse in real projects.
This complete Python tutorial covers 95 topics — from installation and core syntax to OOP, Flask/Django, databases, APIs, data tools, and a final web application project. Beginner-friendly explanations with practical code.
Course roadmap
- Introduction to Python
- What is Python?
- Features of Python
- Python Installation
- Setting Up VS Code / PyCharm
- First Python Program
- Python Syntax
- Variables and Constants in Python
- Data Types in Python
- Type Casting in Python
- Input and Output in Python
- Operators in Python
- Conditional Statements in Python
- if, elif and else in Python
- Loops in Python
- for Loop in Python
- while Loop in Python
- break, continue and pass in Python
- Strings in Python
- String Methods in Python
- Lists in Python
- Tuples in Python
- Sets in Python
- Dictionaries in Python
- List Comprehension in Python
- Dictionary Comprehension in Python
- Functions in Python
- Function Arguments in Python
- *args and **kwargs in Python
- Lambda Functions in Python
- map(), filter() and reduce() in Python
- Scope of Variables in Python
- Modules in Python
- Packages in Python
- pip and Package Management
- Virtual Environment in Python
- Exception Handling in Python
- try, except, else and finally in Python
- File Handling in Python
- Reading and Writing Files in Python
- Working with JSON in Python
- Date and Time in Python
- Regular Expressions in Python
- Object-Oriented Programming in Python
- Classes and Objects in Python
- Constructors in Python
- Inheritance in Python
- Polymorphism in Python
- Encapsulation in Python
- Abstraction in Python
- Magic / Dunder Methods in Python
- Iterators in Python
- Generators in Python
- Decorators in Python
- Context Managers in Python
- Python Type Hints
- Dataclasses in Python
- Working with APIs in Python
- HTTP Requests in Python
- REST API Integration in Python
- SQLite Database with Python
- MySQL with Python
- PostgreSQL with Python
- MongoDB with Python
- Flask Introduction
- Flask Project Setup
- Flask Routing
- Flask Templates
- Flask Forms
- Flask CRUD Application
- Django Introduction
- Django Project Setup
- Django Apps
- Django Models
- Django Views
- Django Templates
- Django Forms
- Django Authentication
- Django REST Framework
- Creating REST APIs with Python
- JWT Authentication in Python
- File Upload in Python Web Apps
- Email Sending in Python
- Web Scraping with Python
- Automation with Python
- Working with Excel Files in Python
- NumPy Basics
- Pandas Basics
- Data Visualization with Matplotlib
- Python Testing with PyTest
- Debugging Python Applications
- Logging in Python
- Python Security Best Practices
- Python Interview Questions
- Final Project – Complete Python Web Application
1. Introduction to Python
Python is a beginner-friendly language used for web development, automation, data science, and APIs. This series covers core syntax, OOP, Flask/Django, databases, and a final web project.
- Install Python and set up an editor.
- Practice core syntax and data structures.
- Build Flask/Django apps and a final project.
Learning path
Basics → data structures → functions/OOP
Files/JSON/regex → databases
Flask/Django → APIs/JWT
Data tools → final web app project
2. What is Python?
Python runs on many platforms and emphasizes readability. You write less boilerplate and can ship scripts, APIs, and apps quickly.
Hello mental model
print('Python is an interpreted language')
# Write code → Python runs it line by line
3. Features of Python
Key strengths include dynamic typing, automatic memory management, batteries-included standard library, and packages via pip for almost every domain.
Feature highlights
- Easy to read syntax
- Large standard library
- Cross-platform
- OOP + functional style
- Huge package ecosystem (pip)
- Great for scripting and backends
4. Python Installation
Download Python from python.org (or use your OS package manager). On Windows, enable “Add Python to PATH”.
- Download Python 3.x LTS/stable.
- Enable PATH on Windows if prompted.
- Verify with `python –version`.
Verify install
python --version
# or
python3 --version
pip --version
5. Setting Up VS Code / PyCharm
Pick an editor, select the Python interpreter, and install helpful extensions (Python, Pylance for VS Code).
VS Code tip
1. Install Python extension
2. Ctrl+Shift+P → Python: Select Interpreter
3. Create/open a .py file and run it
6. First Python Program
Create a `.py` file, add a print statement, and run it from the terminal or your IDE.
hello.py
name = 'Imtiyaj'
print(f'Hello, {name}! Welcome to Python')
# Run: python hello.py
7. Python Syntax
Python uses indentation (spaces) instead of braces. Consistent indentation is required for blocks.
Indentation example
# This is a comment
if True:
print('Indented block')
print('Outside block')
8. Variables and Constants in Python
Python variables are created by assignment. Constants are a convention (UPPER_SNAKE_CASE), not enforced by the language.
Variables
age = 25
price = 99.5
is_active = True
PI = 3.14159 # constant by convention
print(age, price, is_active, PI)
9. Data Types in Python
Use `type()` to inspect values. Python is dynamically typed — the same variable can hold different types over time.
Common types
print(type(10)) # int
print(type(3.14)) # float
print(type('hi')) # str
print(type(True)) # bool
print(type([1, 2])) # list
print(type({'a': 1})) # dict
10. Type Casting in Python
Casting is useful when reading input (always a string) or preparing values for math/APIs.
Casting examples
x = int('42')
y = float('3.5')
z = str(100)
nums = list((1, 2, 3))
print(x, y, z, nums)
11. Input and Output in Python
`input()` returns a string. Convert it before doing math. Prefer f-strings for readable output.
I/O example
name = input('Your name: ')
age = int(input('Your age: '))
print(f'Hello {name}, next year you will be {age + 1}')
12. Operators in Python
Operators combine values and control decisions. Know precedence basics and use parentheses for clarity.
Operator samples
print(10 + 3, 10 // 3, 10 % 3, 2 ** 3)
print(5 > 2 and 5 < 10)
x = 5
x += 2
print(x)
13. Conditional Statements in Python
Conditionals let your program make decisions. Start with `if`, then add `elif`/`else` branches.
Basic condition
score = 75
if score >= 50:
print('Pass')
else:
print('Fail')
14. if, elif and else in Python
Use `elif` for extra checks. Only one branch runs. Keep conditions mutually clear.
Grade example
marks = 82
if marks >= 90:
grade = 'A'
elif marks >= 75:
grade = 'B'
elif marks >= 50:
grade = 'C'
else:
grade = 'F'
print(grade)
15. Loops in Python
Loops process collections and keep running while a condition stays true. Combine with `break`/`continue` when needed.
Loop idea
for i in range(3):
print('tick', i)
16. for Loop in Python
`for item in iterable` is the most common Python loop style. Use `range()` for numeric sequences.
for examples
for n in range(1, 4):
print(n)
for ch in 'hi':
print(ch)
for name in ['Asha', 'Ravi']:
print(name)
17. while Loop in Python
While loops need a changing condition to avoid infinite loops. Great for menus and retries.
while example
count = 3
while count > 0:
print(count)
count -= 1
print('Go!')
18. break, continue and pass in Python
`break` exits a loop early. `continue` jumps to the next iteration. `pass` does nothing (useful as a stub).
Flow controls
for i in range(5):
if i == 1:
continue
if i == 4:
break
print(i)
def todo():
pass # implement later
19. Strings in Python
Strings are immutable sequences of characters. Use quotes, f-strings, indexing, and slices.
String basics
s = 'Python'
print(s[0], s[-1], s[0:3])
print(f'Length: {len(s)}')
20. String Methods in Python
String methods return new strings (original stays unchanged). Chain them carefully.
Useful methods
text = ' Hello World '
print(text.strip().lower())
print(text.replace('World', 'Python'))
parts = 'a,b,c'.split(',')
print('-'.join(parts))
21. Lists in Python
Lists can hold mixed types, grow/shrink, and support indexing, slicing, and methods like append/pop.
List operations
nums = [1, 2, 3]
nums.append(4)
nums.insert(0, 0)
print(nums[1:3])
print(sorted(nums, reverse=True))
22. Tuples in Python
Tuples are like lists but cannot be changed after creation — useful for records and dictionary keys (if hashable).
Tuple example
point = (10, 20)
x, y = point
print(x, y)
print(point[0])
23. Sets in Python
Sets automatically remove duplicates and are fast for membership tests.
Set operations
a = {1, 2, 2, 3}
b = {3, 4}
print(a) # {1, 2, 3}
print(a | b) # union
print(a & b) # intersection
print(2 in a)
24. Dictionaries in Python
Dicts are the go-to structure for JSON-like data. Keys must be hashable (strings/numbers/tuples).
Dict basics
user = {'name': 'Asha', 'age': 28}
user['city'] = 'Pune'
print(user.get('email', 'N/A'))
for key, value in user.items():
print(key, value)
25. List Comprehension in Python
List comprehensions replace many short for-loops. You can also add conditions.
Comprehension
squares = [n * n for n in range(1, 6)]
evens = [n for n in range(10) if n % 2 == 0]
print(squares, evens)
26. Dictionary Comprehension in Python
Dict comprehensions are great for transforming lists into maps or remapping existing dicts.
Dict comprehension
names = ['a', 'b', 'c']
lengths = {name: len(name) for name in names}
print(lengths)
27. Functions in Python
Functions reduce duplication and make programs modular. Prefer clear names and small responsibilities.
Define a function
def greet(name):
return f'Hello, {name}'
print(greet('Imtiyaj'))
28. Function Arguments in Python
Defaults make APIs friendlier. Keyword args improve readability at call sites.
Argument styles
def power(base, exp=2):
return base ** exp
print(power(3))
print(power(2, 5))
print(power(exp=3, base=2))
29. *args and **kwargs in Python
`*args` collects extra positional values into a tuple. `**kwargs` collects keyword args into a dict.
Flexible signature
def demo(*args, **kwargs):
print(args)
print(kwargs)
demo(1, 2, 3, city='Surat', ok=True)
30. Lambda Functions in Python
Lambdas are single-expression functions. Prefer `def` for anything non-trivial.
Lambda examples
add = lambda a, b: a + b
print(add(2, 3))
names = ['zoey', 'amy', 'li']
print(sorted(names, key=lambda s: len(s)))
31. map(), filter() and reduce() in Python
These tools process collections without explicit loops. `reduce` lives in `functools`.
Functional helpers
from functools import reduce
nums = [1, 2, 3, 4, 5]
print(list(map(lambda n: n * 2, nums)))
print(list(filter(lambda n: n % 2 == 0, nums)))
print(reduce(lambda a, b: a + b, nums))
32. Scope of Variables in Python
Names resolve using LEGB. Use `global`/`nonlocal` carefully when you must rebind outer names.
Scope demo
x = 'global'
def outer():
x = 'enclosing'
def inner():
print(x) # enclosing
inner()
outer()
print(x)
33. Modules in Python
Each `.py` file can be a module. Import functions/classes to keep projects organized.
math_utils.py + import
# math_utils.py
def add(a, b):
return a + b
# main.py
from math_utils import add
print(add(2, 3))
34. Packages in Python
A package is a directory of modules. Use clear package names and absolute/relative imports thoughtfully.
Package layout
myapp/
__init__.py
utils/
__init__.py
helpers.py
main.py
# from myapp.utils.helpers import clean_text
35. pip and Package Management
pip installs packages from PyPI. Freeze versions for reproducible environments.
pip commands
pip install requests
pip uninstall requests
pip freeze > requirements.txt
pip install -r requirements.txt
36. Virtual Environment in Python
Always create a virtual environment per project. Activate it before installing packages.
- Create `.venv` with `python -m venv`.
- Activate the environment.
- Install packages inside it only.
Create and activate venv
python -m venv .venv
# Windows PowerShell:
.venvScriptsActivate.ps1
# macOS/Linux:
# source .venv/bin/activate
pip install flask
37. Exception Handling in Python
Exceptions interrupt normal flow. Handle expected failures and re-raise or log unexpected ones.
Basic try/except
try:
value = int('abc')
except ValueError as e:
print('Invalid number:', e)
38. try, except, else and finally in Python
`else` runs when no exception occurs. `finally` always runs — perfect for closing resources.
Full form
try:
n = int('10')
except ValueError:
print('bad')
else:
print('ok', n)
finally:
print('cleanup')
39. File Handling in Python
Prefer `with open(…)` so files close automatically even if errors occur.
Open with context manager
with open('notes.txt', 'w', encoding='utf-8') as f:
f.write('Learning Pythonn')
40. Reading and Writing Files in Python
Choose modes carefully: `r`, `w`, `a`, `rb`, `wb`. Use encoding for text files.
Read and append
with open('notes.txt', 'r', encoding='utf-8') as f:
print(f.read())
with open('notes.txt', 'a', encoding='utf-8') as f:
f.write('Another linen')
41. Working with JSON in Python
JSON maps naturally to Python dicts/lists. Use `json.dumps` / `json.loads` and file helpers.
JSON encode/decode
import json
data = {'name': 'Asha', 'skills': ['python', 'sql']}
text = json.dumps(data, indent=2)
print(text)
print(json.loads(text)['name'])
42. Date and Time in Python
Use `datetime` for timestamps, formatting (`strftime`), and parsing (`strptime`).
datetime basics
from datetime import datetime, timedelta
now = datetime.now()
print(now.strftime('%Y-%m-%d %H:%M'))
print(now + timedelta(days=7))
43. Regular Expressions in Python
Regex is powerful for emails, IDs, and cleanup tasks. Start simple and test patterns carefully.
re examples
import re
text = 'Call me at 98765-43210'
print(re.findall(r'd+', text))
if re.fullmatch(r'[w.-]+@example.com', 'user@example.com'):
print('valid email format')
44. Object-Oriented Programming in Python
OOP helps organize larger programs using encapsulation, inheritance, and polymorphism.
OOP idea
class User:
def __init__(self, name):
self.name = name
def greet(self):
return f'Hi {self.name}'
print(User('Ravi').greet())
45. Classes and Objects in Python
A class defines attributes and methods. An object is one concrete instance of that class.
Class + instance
class Product:
def __init__(self, title, price):
self.title = title
self.price = price
p = Product('Book', 499)
print(p.title, p.price)
46. Constructors in Python
`__init__` runs when you create an object. Set required attributes there.
__init__ example
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
acc = BankAccount('Asha', 1000)
print(acc.owner, acc.balance)
47. Inheritance in Python
Child classes inherit methods/attributes and can override them. Use `super()` to call parents.
Inheritance
class Animal:
def speak(self):
return '...'
class Dog(Animal):
def speak(self):
return 'Woof'
print(Dog().speak())
48. Polymorphism in Python
Polymorphism lets you write code that works with many types sharing an interface.
Polymorphism demo
class Cat:
def speak(self):
return 'Meow'
class Dog:
def speak(self):
return 'Woof'
for animal in (Cat(), Dog()):
print(animal.speak())
49. Encapsulation in Python
Python uses conventions (`_protected`, `__private`) and `@property` instead of strict access modifiers.
Property example
class Account:
def __init__(self, balance):
self._balance = balance
@property
def balance(self):
return self._balance
print(Account(500).balance)
50. Abstraction in Python
Abstraction focuses on what an object does, not how. Use `abc` for formal abstract classes.
Abstract class
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
...
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side * self.side
print(Square(4).area())
51. Magic / Dunder Methods in Python
Dunder methods hook into Python syntax and built-ins so your classes feel native.
__str__ and __len__
class Team:
def __init__(self, members):
self.members = members
def __len__(self):
return len(self.members)
def __str__(self):
return f'Team({len(self)})'
print(len(Team(['a', 'b'])), Team(['a', 'b']))
52. Iterators in Python
Iterators produce values lazily with `next()` until `StopIteration`.
Custom iterator
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
self.current -= 1
return self.current + 1
print(list(Countdown(3)))
53. Generators in Python
Generators pause and resume. Ideal for large streams without loading everything into memory.
Generator function
def countdown(n):
while n > 0:
yield n
n -= 1
for value in countdown(3):
print(value)
54. Decorators in Python
A decorator takes a function and returns a new function. Use `@decorator` syntactic sugar.
Simple decorator
def log(fn):
def wrapper(*args, **kwargs):
print('calling', fn.__name__)
return fn(*args, **kwargs)
return wrapper
@log
def add(a, b):
return a + b
print(add(2, 3))
55. Context Managers in Python
Context managers guarantee cleanup. Files, locks, and DB sessions commonly use them.
custom context manager
from contextlib import contextmanager
@contextmanager
def tag(name):
print(f'<{name}>')
yield
print(f'</{name}>')
with tag('div'):
print('content')
56. Python Type Hints
Type hints do not enforce types at runtime by default, but help editors, mypy, and readers.
Type hints
def area(width: float, height: float) -> float:
return width * height
names: list[str] = ['Asha', 'Ravi']
print(area(3.0, 4.0), names)
57. Dataclasses in Python
Dataclasses auto-create `__init__`, `__repr__`, and more — perfect for structured records.
dataclass example
from dataclasses import dataclass
@dataclass
class User:
name: str
email: str
active: bool = True
print(User('Asha', 'asha@example.com'))
58. Working with APIs in Python
APIs usually return JSON. You send HTTP requests, parse responses, and handle errors/status codes.
API mindset
Request → HTTP method + URL + headers/body
Response → status code + JSON/text
Handle 2xx success and 4xx/5xx errors
59. HTTP Requests in Python
`requests` simplifies HTTP calls. Always check `response.ok` / status codes.
GET JSON
import requests
r = requests.get('https://jsonplaceholder.typicode.com/posts/1', timeout=10)
r.raise_for_status()
print(r.json()['title'])
60. REST API Integration in Python
REST uses resource URLs and HTTP verbs. Send JSON with correct headers and parse responses.
POST JSON example
import requests
payload = {'title': 'foo', 'body': 'bar', 'userId': 1}
r = requests.post(
'https://jsonplaceholder.typicode.com/posts',
json=payload,
timeout=10,
)
print(r.status_code, r.json())
61. SQLite Database with Python
SQLite is file-based and perfect for learning SQL and small apps. Use parameterized queries.
sqlite3 CRUD sketch
import sqlite3
conn = sqlite3.connect('app.db')
cur = conn.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)')
cur.execute('INSERT INTO users (name) VALUES (?)', ('Asha',))
conn.commit()
print(cur.execute('SELECT * FROM users').fetchall())
conn.close()
62. MySQL with Python
Install a MySQL driver, connect with credentials from environment variables, and use parameterized SQL.
PyMySQL sketch
# pip install PyMySQL
import pymysql
conn = pymysql.connect(host='127.0.0.1', user='root', password='', database='demo')
with conn.cursor() as cur:
cur.execute('SELECT NOW()')
print(cur.fetchone())
conn.close()
63. PostgreSQL with Python
PostgreSQL is a robust production database. Keep credentials in env vars and close connections cleanly.
psycopg sketch
# pip install psycopg[binary]
import psycopg
with psycopg.connect('postgresql://user:pass@phpcodeinformation.com/dbname') as conn:
with conn.cursor() as cur:
cur.execute('SELECT version()')
print(cur.fetchone())
64. MongoDB with Python
MongoDB stores JSON-like documents. PyMongo provides insert/find/update/delete APIs.
PyMongo sketch
# pip install pymongo
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017')
db = client['demo']
db.users.insert_one({'name': 'Asha'})
print(list(db.users.find({}, {'_id': 0})))
65. Flask Introduction
Flask gives you routing and responses with minimal setup. Extend it with extensions as you grow.
Tiny Flask app
from flask import Flask
app = Flask(__name__)
@app.get('/')
def home():
return 'Hello Flask'
# flask --app app run
66. Flask Project Setup
Use venv, install Flask, and keep config in environment variables for clean local/prod setups.
Setup commands
python -m venv .venv
.venvScriptsActivate.ps1
pip install flask python-dotenv
# create app.py and run:
flask --app app run --debug
67. Flask Routing
Routes connect HTTP paths/methods to Python functions that return responses.
Routes
from flask import Flask
app = Flask(__name__)
@app.get('/hello/<name>')
def hello(name):
return f'Hello {name}'
@app.post('/items')
def create_item():
return {'ok': True}, 201
68. Flask Templates
Templates live in `templates/`. Use `render_template` and `{{ }}` / `{% %}` syntax.
Render template
from flask import render_template
@app.get('/about')
def about():
return render_template('about.html', title='About')
69. Flask Forms
Read `request.form`, validate fields, then redirect with flash messages on success.
Form POST
from flask import request, redirect, url_for, flash
@app.route('/contact', methods=['GET', 'POST'])
def contact():
if request.method == 'POST':
email = request.form.get('email', '').strip()
if not email:
flash('Email required')
return redirect(url_for('contact'))
flash('Thanks!')
return redirect(url_for('contact'))
return render_template('contact.html')
70. Flask CRUD Application
CRUD apps teach routing, templates/JSON, validation, and persistence (SQLite/SQLAlchemy).
In-memory CRUD sketch
items = {}
@app.get('/api/items')
def list_items():
return list(items.values())
@app.post('/api/items')
def add_item():
data = request.get_json() or {}
item_id = str(len(items) + 1)
items[item_id] = {'id': item_id, 'title': data.get('title')}
return items[item_id], 201
71. Django Introduction
Django includes ORM, admin, auth, and templates. Great for larger products and rapid development.
Django vs Flask (short)
Flask: minimal, flexible, pick your tools
Django: full stack defaults (ORM, admin, auth)
Choose based on project size and needs
72. Django Project Setup
Install Django in a venv, start a project, and run migrations for built-in apps.
Start project
pip install django
django-admin startproject config .
python manage.py migrate
python manage.py runserver
73. Django Apps
Projects contain apps (blog, accounts, shop). Register apps in `INSTALLED_APPS`.
Create an app
python manage.py startapp blog
# add 'blog' to INSTALLED_APPS in settings.py
74. Django Models
Models describe fields and behavior. Migrate after changes to update the database schema.
Post model
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
75. Django Views
Views receive a request and return a response (HTML or JSON). Keep them thin; push logic to models/services.
Function view
from django.http import HttpResponse
def home(request):
return HttpResponse('Hello Django')
76. Django Templates
Use `{% extends %}` layouts and `{{ variable }}` output. Escape is on by default for safety.
Template render
from django.shortcuts import render
def home(request):
return render(request, 'home.html', {'title': 'Home'})
77. Django Forms
Forms handle cleaning/validation and can save model instances via ModelForm.
ModelForm sketch
from django import forms
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title', 'body']
78. Django Authentication
Django ships with User model, login views, password hashing, and `@login_required`.
Protect a view
from django.contrib.auth.decorators import login_required
@login_required
def dashboard(request):
return render(request, 'dashboard.html')
79. Django REST Framework
DRF turns Django models into JSON APIs quickly with browsable API and auth support.
Install DRF
pip install djangorestframework
# add 'rest_framework' to INSTALLED_APPS
80. Creating REST APIs with Python
Whether Flask or DRF, keep resources clear: list/create on collections, retrieve/update/delete on items.
Flask JSON endpoint
from flask import jsonify, request
@app.get('/api/posts')
def posts():
return jsonify([{'id': 1, 'title': 'Hello'}])
81. JWT Authentication in Python
Issue a signed JWT on login and require `Authorization: Bearer <token>` on protected routes.
PyJWT sketch
# pip install PyJWT
import jwt
from datetime import datetime, timedelta, timezone
def create_token(user_id: int, secret: str) -> str:
payload = {
'sub': user_id,
'exp': datetime.now(timezone.utc) + timedelta(hours=24),
}
return jwt.encode(payload, secret, algorithm='HS256')
82. File Upload in Python Web Apps
Validate file type/size, sanitize filenames, and store uploads outside executable paths when possible.
Flask upload
from flask import request
from werkzeug.utils import secure_filename
@app.post('/upload')
def upload():
f = request.files.get('file')
if not f:
return {'error': 'No file'}, 400
f.save(f'uploads/{secure_filename(f.filename)}')
return {'ok': True}
83. Email Sending in Python
Use SMTP credentials from environment variables. Prefer app passwords / API mail providers in production.
smtplib sketch
import smtplib
from email.message import EmailMessage
msg = EmailMessage()
msg['Subject'] = 'Welcome'
msg['From'] = 'noreply@example.com'
msg['To'] = 'user@example.com'
msg.set_content('Thanks for signing up!')
# with smtplib.SMTP('smtp.example.com', 587) as s:
# s.starttls()
# s.login(user, password)
# s.send_message(msg)
84. Web Scraping with Python
Scrape only when allowed. Prefer official APIs. Parse HTML carefully and throttle requests.
BeautifulSoup sketch
# pip install beautifulsoup4 requests
import requests
from bs4 import BeautifulSoup
html = requests.get('https://example.com', timeout=10).text
soup = BeautifulSoup(html, 'html.parser')
print(soup.title.text)
85. Automation with Python
Python shines at glue code — combining files, APIs, and OS tasks into one script.
Rename files sketch
from pathlib import Path
folder = Path('invoices')
for i, path in enumerate(folder.glob('*.pdf'), start=1):
path.rename(folder / f'invoice-{i:03d}.pdf')
86. Working with Excel Files in Python
Use pandas for analysis-friendly tables; openpyxl for formatted workbooks.
pandas Excel
# pip install pandas openpyxl
import pandas as pd
df = pd.DataFrame({'name': ['Asha', 'Ravi'], 'score': [90, 88]})
df.to_excel('scores.xlsx', index=False)
print(pd.read_excel('scores.xlsx'))
87. NumPy Basics
NumPy arrays support vectorized math — much faster than Python loops for large numeric data.
NumPy array
# pip install numpy
import numpy as np
a = np.array([1, 2, 3, 4])
print(a * 2)
print(a.mean(), a.max())
88. Pandas Basics
Pandas is the standard tool for CSV/Excel analysis in Python.
DataFrame basics
# pip install pandas
import pandas as pd
df = pd.DataFrame({'city': ['Pune', 'Surat', 'Pune'], 'sales': [10, 15, 7]})
print(df.groupby('city')['sales'].sum())
89. Data Visualization with Matplotlib
Start with line/bar charts. Label axes and titles so charts are understandable.
Simple plot
# pip install matplotlib
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [3, 5, 4])
plt.title('Demo')
plt.xlabel('x')
plt.ylabel('y')
plt.show()
90. Python Testing with PyTest
Tests catch regressions early. Keep them fast and focused on one behavior each.
test_math.py
# pip install pytest
def add(a, b):
return a + b
def test_add():
assert add(2, 3) == 5
# pytest
91. Debugging Python Applications
Reproduce the bug, isolate the failing input, inspect state, fix, then add a test.
pdb breakpoint
def broken(n):
breakpoint() # or import pdb; pdb.set_trace()
return 10 / n
# broken(0)
92. Logging in Python
Use INFO/WARNING/ERROR levels. Configure formatters and handlers for files or stdout.
logging basics
import logging
logging.basicConfig(level=logging.INFO, format='%(levelname)s %(message)s')
logging.info('Server started')
logging.error('Payment failed')
93. Python Security Best Practices
Never hardcode secrets. Validate input, hash passwords, keep dependencies updated, and use HTTPS.
Security checklist
- Store secrets in environment variables
- Hash passwords (bcrypt/argon2)
- Parameterize SQL queries
- Validate/sanitize uploads
- Keep packages updated
- Use HTTPS in production
94. Python Interview Questions
Be ready to explain mutability, GIL/basics of concurrency, decorators, generators, and Flask vs Django.
Sample Q&A
Q: List vs tuple?
A: Lists mutable; tuples immutable.
Q: What is a decorator?
A: A function that wraps another function.
Q: *args vs **kwargs?
A: Extra positional vs keyword arguments.
Q: GIL?
A: CPython lock limiting one bytecode thread at a time.
95. Final Project – Complete Python Web Application
Combine everything: venv, Flask or Django, database models, authentication, forms/API, file upload, and deployment-ready settings.
- Choose Flask or Django.
- Design models and auth.
- Implement web CRUD + API.
- Add tests for core flows.
- Document and prepare deploy.
Final project scope
1. User registration/login
2. CRUD for a main resource (posts/tasks)
3. Validation + flash/error messages
4. REST JSON endpoints (+ optional JWT)
5. File upload for images/docs
6. Logging + .env config
7. README + requirements.txt
Suggested Flask routes
@app.post('/api/login')
@app.get('/api/items')
@app.post('/api/items')
@app.put('/api/items/<id>')
@app.delete('/api/items/<id>')
Conclusion
You now have a full Python path: language fundamentals, OOP, files/APIs/databases, Flask and Django, data basics, testing, and security. Finish with the complete web application project to lock in the skills.