PYTHON

Dive into Python programming basics, including syntax, data
structures, and scripting for automation or backend tasks.

Python Topics with Definitions, Explanations & Practice Programs

1. What is Python?

Python is a high‑level, interpreted, general‑purpose programming language known for its readability and vast standard library.

# hello.py
print("Hello, Python!")
2. Installing Python & virtualenv

Download from python.org or install via package manager. Use python -m venv venv to create isolated environments.

python -m venv venv
source venv/bin/activate  # Windows: venv\Scripts\activate
3. Python REPL

The Read‑Eval‑Print‑Loop lets you test snippets quickly.

$ python
>>> 2 + 3
5
4. Variables & Data Types

Dynamic typing—no need to declare types explicitly (int, float, str, bool, list, tuple, dict, set).

x = 10  # int
pi = 3.14  # float
name = "Alice"  # str
5. Basic I/O

input() reads user input; print() writes to stdout.

name = input("Your name: ")
print("Hi", name)
6. Arithmetic Operators

+ - * / // % ** perform maths; // is floor‑division, ** exponentiation.

area = 0.5 * base * height
7. String Methods & f‑strings

Use upper(), replace(), slicing, and f‑strings for formatting.

msg = f"{name.upper()} scored {marks}/100"
8. Conditional Statements

if elif else control flow.

if temp > 40:
  print("Hot")
elif temp > 20:
  print("Warm")
else:
  print("Cold")
9. Loops (for, while)

for iterates over sequences; while repeats until condition false.

for i in range(1, 6):
  print(i**2)
10. List Comprehensions

Concise way to build lists from iterables.

squares = [i*i for i in range(10) if i % 2 == 0]
11. Tuples & Unpacking

Immutable ordered collections; convenient for returning multiple values.

point = (3, 4)
x, y = point
12. Dictionaries

Key‑value mapping; constant‑time lookup.

student = {"id": 101, "name": "Ana", "cgpa": 8.9}
for k, v in student.items():
  print(k, v)
13. Sets & Set Operations

Unordered collection of unique items; supports union, intersection.

odd = {1, 3, 5}; even = {2, 4, 6}
print(odd | even)
14. Functions & Docstrings

Reusable blocks; document with triple‑quoted strings.

def add(a, b):
  """Return sum of a and b."""
  return a + b
15. Lambda, map(), filter()

Anonymous functions combined with functional helpers.

doubles = list(map(lambda x: 2*x, [1,2,3]))
evens  = list(filter(lambda x: x%2==0, range(10)))
16. Exception Handling

Gracefully catch runtime errors using try‑except‑else‑finally.

try:
  ans = 10 / 0
except ZeroDivisionError as e:
  print("Cannot divide by zero.")
finally:
  print("Done")
17. File I/O

Read & write files with context managers to ensure proper closing.

with open("data.txt") as f:
  lines = f.readlines()
18. Modules & Packages

Organise code into separate files; import with import mod or from mod import func.

# utils.py
def greet():
  print("Hi")
# main.py
import utils
utils.greet()
19. Virtual Environment & pip

Manage dependencies; pip install requests installs packages from PyPI.

pip freeze > requirements.txt
20. Object‑Oriented Programming

Classes encapsulate data and behaviour; supports inheritance and polymorphism.

class Vehicle:
  def __init__(self, name): self.name = name
  def move(self): print(self.name, "moves")
class Car(Vehicle): pass
Car("Tesla").move()
21. @property and Getters/Setters

Control attribute access while keeping dot syntax.

class Circle:
  def __init__(self, r): self._r = r
  @property
  def area(self): return 3.14 * self._r**2
22. Generators & yield

Lazy iterables that save memory.

def fib(n):
  a, b = 0, 1
  for _ in range(n):
    yield a
    a, b = b, a+b
23. Decorators

Functions that modify behaviour of other functions.

def timer(fn):
  import time
  def wrap(*a, **kw):
    s = time.time(); result = fn(*a, **kw);
    print("took", time.time()-s); return result
  return wrap
24. Context Managers & with

Automate setup/teardown by defining __enter__/__exit__.

from contextlib import contextmanager
@contextmanager
def open_db():
  print("connect"); yield; print("close")
25. Regular Expressions (re)

Powerful pattern matching and text processing.

import re
emails = re.findall(r"[a-zA-Z0-9._%+-]+@[\w.-]+", text)
26. JSON Handling

Convert between Python objects and JSON strings with json module.

import json
data = json.loads('{"x":1}')
print(json.dumps(data, indent=2))
27. HTTP Requests (requests)

Send/receive web data easily (third‑party library).

import requests
r = requests.get("https://api.github.com")
print(r.status_code)
28. Multithreading vs Multiprocessing

threading for I/O‑bound; multiprocessing for CPU‑bound tasks.

from multiprocessing import Pool
print(Pool().map(lambda x: x*x, range(5)))
29. Asynchronous Programming (asyncio)

Handle thousands of concurrent I/O operations using async def and await.

import asyncio, aiohttp
async def fetch(url):
  async with aiohttp.ClientSession() as s:
    async with s.get(url) as r: return await r.text()
30. Practice Problem: Quadratic Solver

Task: Write a program that solves ax² + bx + c = 0 for real/complex roots.

import cmath
a,b,c = 1, -3, 2
d = cmath.sqrt(b*b - 4*a*c)
root1 = (-b + d)/(2*a)
root2 = (-b - d)/(2*a)
print(root1, root2)

Python Advanced Topics Continued (31–50)

31. Python zip()

Combines multiple iterables into tuples, pairing elements by position.

names = ['Alice', 'Bob']
scores = [85, 92]
for name, score in zip(names, scores):
  print(name, "scored", score)
32. Python enumerate()

Adds a counter while iterating over an iterable.

colors = ['Red', 'Green', 'Blue']
for index, color in enumerate(colors):
  print(index, color)
33. Python isinstance() & type()

Check object type at runtime for type-safe code.

x = 5
print(isinstance(x, int))
print(type(x) == int)
34. Python sys.argv

Used to pass command-line arguments to a script.

import sys
print("Arguments:", sys.argv)
35. Python os module

Provides access to the operating system (file paths, directories, etc.).

import os
print("Current Dir:", os.getcwd())
os.mkdir("new_folder")
36. Python shutil module

Used for high-level file operations like copy, move, delete.

import shutil
shutil.copy("file1.txt", "file2.txt")
37. Python datetime module

Used to work with date and time objects.

from datetime import datetime
now = datetime.now()
print(now.strftime("%d-%m-%Y %H:%M:%S"))
38. Python time module

Provides functions to track and manipulate time (e.g., sleep).

import time
print("Wait 2 seconds...")
time.sleep(2)
print("Done")
39. Python math module

Standard math library for advanced calculations.

import math
print(math.sqrt(16))
print(math.factorial(5))
40. Python statistics module

Provides basic statistical functions like mean, median, mode.

import statistics
data = [10, 20, 30]
print("Mean:", statistics.mean(data))
41. Python random module

Generates pseudo-random numbers and choices.

import random
print(random.randint(1, 10))
print(random.choice(["red", "green", "blue"]))
42. Python itertools module

Offers fast, memory-efficient tools for iterators (combinations, permutations).

from itertools import permutations
for p in permutations([1, 2, 3]):
  print(p)
43. Python assert statement

Used to test if a condition is true; helps in debugging.

x = 10
assert x > 0, "x must be positive"
44. Python unittest module

Framework for writing and running tests for your code.

import unittest
class TestSum(unittest.TestCase):
  def test_add(self): self.assertEqual(1+2, 3)
45. Python doctest module

Tests embedded in docstrings using example-based testing.

def add(a, b):
  """Returns sum
  >>> add(2, 3)
  5
  """
  return a + b
46. Python logging module

Provides a flexible system for logging messages.

import logging
logging.basicConfig(level=logging.INFO)
logging.info("This is info")
47. Python sys.exit()

Gracefully exits the program with an optional status code.

import sys
if error: sys.exit("Exiting due to error.")
48. Python __name__ == "__main__"

Checks whether script is being run directly or imported.

if __name__ == "__main__":
  main()
49. Python csv module

Read and write CSV (Comma Separated Values) files.

import csv
with open('data.csv') as f:
  reader = csv.reader(f)
  for row in reader:
    print(row)
50. Python pickle module

Serialize and deserialize Python objects to store them in files.

import pickle
with open("obj.pkl", "wb") as f:
  pickle.dump({"a": 1}, f)

Python Advanced Topics (51–70)

51. NumPy Arrays

NumPy provides high-performance multi-dimensional arrays and numerical operations.

import numpy as np
a = np.array([1, 2, 3])
print(a * 2)
52. NumPy Array Slicing

Allows accessing subarrays using indices and ranges.

a = np.array([1,2,3,4,5])
print(a[1:4])
53. Pandas DataFrame

DataFrame is a 2D tabular data structure with labeled axes (rows & columns).

import pandas as pd
df = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Score': [90, 80]})
print(df)
54. Pandas Series

One-dimensional labeled array capable of holding any data type.

s = pd.Series([1, 3, 5])
print(s)
55. Pandas Filtering

Apply conditions to filter rows in DataFrames.

print(df[df['Score'] > 85])
56. Matplotlib Plotting

Matplotlib is used to generate plots, charts, and visualizations.

import matplotlib.pyplot as plt
plt.plot([1,2,3], [4,5,6])
plt.show()
57. SQLite with Python

SQLite is a lightweight SQL database embedded into Python via the sqlite3 module.

import sqlite3
conn = sqlite3.connect("test.db")
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS student (id INT, name TEXT)")
conn.commit()
58. Tkinter GUI

Tkinter is the standard GUI toolkit for Python to build desktop apps.

from tkinter import *
root = Tk()
Label(root, text="Hello GUI").pack()
root.mainloop()
59. Web Scraping with BeautifulSoup

BeautifulSoup is used to extract data from HTML and XML documents.

from bs4 import BeautifulSoup
soup = BeautifulSoup("<html><h1>Hello</h1></html>", 'html.parser')
print(soup.h1.text)
60. Flask Framework

Flask is a lightweight web framework for building web apps and APIs.

from flask import Flask
app = Flask(__name__)
@app.route("/")
def home(): return "Hello Flask"
61. Flask Routing

Define routes using decorators that match URLs to functions.

@app.route("/user/<name>")
def greet(name): return f"Hello {name}"
62. Django Framework

Django is a high-level Python web framework for rapid development and clean design.

# In views.py
from django.http import HttpResponse
def index(request): return HttpResponse("Welcome to Django")
63. Django Models

Django models define the structure of database tables.

from django.db import models
class Student(models.Model):
  name = models.CharField(max_length=50)
64. Django Admin Panel

Auto-generated interface for managing models.

# In admin.py
from .models import Student
admin.site.register(Student)
65. Sending Emails with smtplib

Python’s built-in SMTP library for sending emails through code.

import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)
66. Working with CSV Files

CSV files can be processed with the built-in csv module or Pandas.

import csv
with open('data.csv') as f:
  reader = csv.reader(f)
  for row in reader: print(row)
67. Working with JSON Files

JSON is widely used for config files and API responses.

import json
data = {"name": "John"}
with open("data.json", "w") as f:
  json.dump(data, f)
68. Python Multithreading

Used to perform multiple I/O operations simultaneously in a single process.

import threading
def task(): print("Running thread")
threading.Thread(target=task).start()
69. Python Multiprocessing

Used for parallel CPU-bound processing across multiple processes.

from multiprocessing import Process
def job(): print("Child Process")
p = Process(target=job)
p.start(); p.join()
70. Python Dataclasses

Introduced in Python 3.7, dataclasses simplify class creation for data storage.

from dataclasses import dataclass
@dataclass
class Student:
  name: str
  age: int

Python Topics (71–90)

71. Python Virtual Environment (venv)

Creates isolated environments for different projects to manage dependencies separately.

python -m venv myenv
source myenv/bin/activate (Linux/Mac)
myenv\Scripts\activate (Windows)
72. Python Decorators

Functions that modify the behavior of other functions using @ syntax.

def decorator(func):
  def wrapper():
    print("Before")
    func()
    print("After")
  return wrapper

@decorator
def greet(): print("Hello")
greet()
73. Python Generators

Generators use yield to produce a sequence of values lazily (on demand).

def countdown(n):
  while n > 0:
    yield n
    n -= 1

for i in countdown(3): print(i)
74. Python Iterator Protocol

Defines how to access items in a container using __iter__() and __next__().

class Counter:
  def __init__(self): self.count = 0
  def __iter__(self): return self
  def __next__(self):
    if self.count < 3:
      self.count += 1
      return self.count
    else: raise StopIteration

for i in Counter(): print(i)
75. Lambda Functions

Small anonymous functions using lambda keyword.

square = lambda x: x * x
print(square(5))
76. map(), filter(), reduce()

Functional programming tools for applying functions to iterables.

from functools import reduce
nums = [1,2,3,4]
print(list(map(lambda x: x*2, nums)))
print(list(filter(lambda x: x%2==0, nums)))
print(reduce(lambda x,y: x+y, nums))
77. Python Packaging with setup.py

Create distributable Python packages using setuptools.

from setuptools import setup
setup(name='mypackage', version='1.0', py_modules=['mymodule'])
78. Python PyPI and pip

pip is used to install packages from the Python Package Index (PyPI).

pip install numpy
pip uninstall requests
79. Python Wheel Files (.whl)

Binary distribution format for faster installation of Python packages.

pip install mypackage.whl
80. Python PyInstaller

Bundles Python apps into standalone executables.

pip install pyinstaller
pyinstaller myscript.py
81. Python argparse

Used to create command-line tools with argument parsing.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("name")
args = parser.parse_args()
print(args.name)
82. Python JSON Handling

Read/write JSON data using the built-in json module.

import json
data = {"a": 10}
json_str = json.dumps(data)
print(json.loads(json_str))
83. Python Logging Levels

Levels: DEBUG, INFO, WARNING, ERROR, CRITICAL.

import logging
logging.basicConfig(level=logging.WARNING)
logging.warning("This is a warning")
84. Python Unit Test Discovery

Auto-discover test files using unittest framework.

python -m unittest discover
85. Python with Statement (Context Manager)

Used to manage resources like files, automatically closes them.

with open("file.txt") as f:
  data = f.read()
86. Python __init__.py

Marks a directory as a Python package; can include initialization code.

# __init__.py
print("Initializing package")
87. Python Jupyter Notebook

Interactive coding environment, great for data science and teaching.

pip install notebook
jupyter notebook
88. Python Magic Methods

Special methods like __str__, __add__, etc., that add functionality to classes.

class Person:
  def __str__(self): return "This is a Person"
89. Python Type Hints

Optional type annotations to improve code clarity and tooling.

def greet(name: str) -> str:
  return "Hi " + name
90. Python Requirements File

Lists all dependencies of a project; used by pip to install them.

# requirements.txt
numpy==1.21.0
pandas==1.3.0

pip install -r requirements.txt

Python Final Topics (91–100)

91. Python __slots__

Used to limit the attributes an object can have, reducing memory usage.

class Person:
  __slots__ = ['name', 'age']
  def __init__(self, name, age):
    self.name = name
    self.age = age
92. Python Property Decorator

Provides controlled access to class attributes via getter/setter methods.

class Circle:
  def __init__(self, radius): self._radius = radius
  @property
  def radius(self): return self._radius
93. Python Descriptors

Advanced feature to customize attribute access using __get__, __set__.

class Descriptor:
  def __get__(self, obj, type=None): return "Got it"

class Demo:
  x = Descriptor()

print(Demo().x)
94. Python __dict__

Stores an object’s attributes in a dictionary format.

class Car:
  def __init__(self): self.color = "red"
print(Car().__dict__)
95. Python __repr__ vs __str__

__str__ is used for user-friendly string, __repr__ for developer/debugging.

class Data:
  def __str__(self): return "User View"
  def __repr__(self): return "Developer View"
96. Python Garbage Collection

Automatically reclaims unused memory by deleting unreachable objects.

import gc
gc.collect() # Manually trigger garbage collection
97. Python WeakRef Module

Used to create weak references to objects, avoiding memory leaks in caches.

import weakref
class MyClass: pass
obj = MyClass()
r = weakref.ref(obj)
print(r())
98. Python MemoryView

Used to access the internal data of an object without copying.

data = bytearray(b'abc')
mv = memoryview(data)
print(mv[0]) # ASCII of 'a'
99. Python Contextlib Module

Helps create context managers (like with statements) easily.

from contextlib import contextmanager
@contextmanager
def open_file(name):
  f = open(name)
  yield f
  f.close()
100. Python AsyncIO

Supports asynchronous programming for handling I/O-bound tasks efficiently.

import asyncio
async def main():
  print("Waiting...")
  await asyncio.sleep(1)
  print("Done")

asyncio.run(main())
Python Reference Links

📘 Official Python Docs: https://docs.python.org/3/

🐍 W3Schools Python: https://www.w3schools.com/python/

🎓 GeeksforGeeks Python: https://www.geeksforgeeks.org/python-programming-language/

💡 Real Python Tutorials: https://realpython.com/

📒 Jupyter Notebooks: https://jupyter.org/

📦 PyPI (Package Index): https://pypi.org/