Python Programming Notes
A Comprehensive Reference Guide
1. Introduction to Python
• Python is a high-level, interpreted, general-purpose programming language.
• Created by Guido van Rossum and first released in 1991.
• Known for its clean syntax and readability.
• Supports multiple programming paradigms: procedural, OOP, and functional.
• Widely used in web dev, data science, AI/ML, automation, and scripting.
2. Basic Syntax & Data Types
2.1 Variables & Assignment
Python uses dynamic typing — no need to declare variable types.
x = 10 # integer
name = 'Alice' # string
pi = 3.14 # float
is_active = True # boolean
2.2 Data Types
Type Example Description
int x = 5 Integer numbers
float x = 3.14 Decimal numbers
str x = "hello" Text / string
bool x = True Boolean (True/False)
list x = [1, 2, 3] Ordered, mutable sequence
tuple x = (1, 2, 3) Ordered, immutable sequence
dict x = {"a": 1} Key-value pairs
set x = {1, 2, 3} Unordered, unique values
3. Control Flow
3.1 Conditional Statements
if x > 0:
print('Positive')
elif x == 0:
print('Zero')
else:
print('Negative')
3.2 Loops
for loop: Iterates over a sequence
for i in range(5):
print(i) # 0, 1, 2, 3, 4
while loop: Runs while condition is True
count = 0
while count < 3:
count += 1
Loop control: break (exit), continue (skip), pass (placeholder)
4. Functions
Functions are defined with the def keyword. Python supports default args, *args, and **kwargs.
def greet(name, greeting='Hello'):
return f'{greeting}, {name}!'
# *args - variable positional arguments
def total(*nums):
return sum(nums)
# **kwargs - variable keyword arguments
def display(**info):
for k, v in [Link]():
print(f'{k}: {v}')
Lambda: Anonymous one-line function: square = lambda x: x * x
5. Object-Oriented Programming (OOP)
5.1 Classes & Objects
class Animal:
def __init__(self, name, sound):
[Link] = name
[Link] = sound
def speak(self):
return f'{[Link]} says {[Link]}'
dog = Animal('Dog', 'Woof')
print([Link]()) # Dog says Woof
5.2 Inheritance
class Dog(Animal):
def fetch(self):
return f'{[Link]} fetches the ball!'
5.3 Key OOP Concepts
• Encapsulation: Bundling data and methods in a class.
• Inheritance: Child class inherits from parent class.
• Polymorphism: Same method behaves differently in different classes.
• Abstraction: Hiding implementation details from the user.
6. Collections & Comprehensions
6.1 List Methods
lst = [3, 1, 4, 1, 5]
[Link](9) # add to end
[Link]() # sort in place
[Link]() # remove last element
[Link](1) # remove first occurrence
len(lst) # get length
6.2 Dictionary Methods
d = {"name": "Rajasree", "age": 22}
[Link]() # dict_keys(['name', 'age'])
[Link]() # dict_values(['Rajasree', 22])
[Link]() # key-value pairs
[Link]("city", "Unknown") # safe access with default
6.3 Comprehensions
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
upper = {k: [Link]() for k, v in [Link]() if isinstance(v, str)}
7. File Handling
# Reading a file
with open('[Link]', 'r') as f:
content = [Link]()
# Writing a file
with open('[Link]', 'w') as f:
[Link]('Hello, World!')
# Appending to a file
with open('[Link]', 'a') as f:
[Link]('New log entry\n')
Modes: 'r' read | 'w' write (overwrite) | 'a' append | 'rb'/'wb' binary
8. Exception Handling
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f'Error: {e}')
except (TypeError, ValueError) as e:
print(f'Type/Value error: {e}')
else:
print('No error occurred')
finally:
print('This always runs')
• Use specific exceptions before generic ones.
• Raise your own: raise ValueError('Invalid input')
• Custom exceptions: class MyError(Exception): pass
9. Modules & Libraries
9.1 Importing
import math
from os import path
import numpy as np
from datetime import datetime, timedelta
9.2 Useful Standard Library Modules
Module Use Case
os / sys File system, paths, system operations
math Mathematical functions (sqrt, ceil, floor, pi)
datetime Date and time manipulation
re Regular expressions / pattern matching
json Parse and generate JSON data
random Random number generation
collections Counter, defaultdict, OrderedDict, deque
itertools Efficient looping tools (chain, product, etc.)
csv Read and write CSV files
pathlib Object-oriented filesystem paths
10. Pythonic Tips & Best Practices
• Use list/dict/set comprehensions instead of explicit loops where readable.
• Use with statement for file handling and context managers.
• Prefer f-strings over .format() or % formatting.
• Follow PEP 8 style guide: snake_case for variables, PascalCase for classes.
• Use enumerate() instead of range(len(list)) for indexed loops.
• Use zip() to iterate over multiple lists in parallel.
• Use _ for throwaway variables: for _ in range(5): ...
• Virtual environments (venv) keep dependencies isolated per project.
• Type hints improve code readability: def greet(name: str) -> str:
• Use docstrings to document functions, classes, and modules.
Happy Coding with Python!