0% found this document useful (0 votes)
2 views36 pages

Python Notes

This document is a comprehensive study guide for Python, covering topics from fundamentals to advanced concepts. It includes sections on variables, control flow, functions, object-oriented programming, file handling, libraries like NumPy and Pandas, and APIs. The guide also provides best practices, examples, and practice questions to aid in learning.

Uploaded by

abhinavkumar2956
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views36 pages

Python Notes

This document is a comprehensive study guide for Python, covering topics from fundamentals to advanced concepts. It includes sections on variables, control flow, functions, object-oriented programming, file handling, libraries like NumPy and Pandas, and APIs. The guide also provides best practices, examples, and practice questions to aid in learning.

Uploaded by

abhinavkumar2956
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

■ Complete Python

Notes
Beginner to Advanced

Variables & Data Types Control Flow Functions & OOP

File & Exception Handling NumPy & Pandas APIs & Automation

Comprehensive Study Guide & Reference Handbook


Covers syntax · examples · best practices · practice questions · cheat sheet
Table of Contents
1. Fundamentals
1.1 What is Python?
1.2 Setup & Installation
1.3 Variables & Data Types
1.4 Operators

2. Control Flow
2.1 Conditionals (if/elif/else)
2.2 Loops (for, while)
2.3 Break, Continue, Pass

3. Functions & Modules


3.1 Defining Functions
3.2 Arguments & Return Values
3.3 Lambda Functions
3.4 Modules & Packages

4. Data Structures
4.1 Lists
4.2 Tuples
4.3 Dictionaries
4.4 Sets

5. Object-Oriented Programming
5.1 Classes & Objects
5.2 Inheritance
5.3 Polymorphism
5.4 Encapsulation

6. File Handling
6.1 Reading & Writing Files
6.2 CSV & JSON Files
7. Exception Handling
7.1 try/except/finally
7.2 Custom Exceptions

8. Libraries: NumPy & Pandas


8.1 NumPy Arrays
8.2 Pandas DataFrames
8.3 Data Analysis

9. APIs & Automation


9.1 requests Library
9.2 REST APIs
9.3 Basic Automation

10. Advanced Topics


10.1 Comprehensions
10.2 Generators
10.3 Decorators
10.4 Context Managers

11. Practice Questions


Beginner · Intermediate · Advanced
12. Cheat Sheet
Quick Reference Tables
Chapter 1: Fundamentals

1.1 What is Python?


■ Definition: Python is a high-level, interpreted, general-purpose programming language known for its
clear syntax and readability. Created by Guido van Rossum and first released in 1991.

Python follows the principle: 'There should be one — and preferably only one — obvious way to do it.' It
supports multiple programming paradigms including procedural, object-oriented, and functional
programming.

Key Characteristics
Feature Description

Interpreted Code is executed line-by-line; no compilation step needed

Dynamically typed Variable types are determined at runtime

Garbage collected Memory management is automatic

Cross-platform Runs on Windows, macOS, Linux without modification

Extensive stdlib Batteries included — rich standard library

1.2 Setup & Installation


Install Python from [Link]. Verify with:

■ Terminal
python --version # e.g. Python 3.11.4
python -m pip --version # check pip package manager

Create a virtual environment (recommended for every project):

■ Virtual Environment Setup


python -m venv my_env # create environment
source my_env/bin/activate # activate (Linux/macOS)
my_env\Scripts\activate # activate (Windows)
pip install package_name # install packages
deactivate # exit environment

1.3 Variables & Data Types


■ Definition: A variable is a named reference to a value stored in memory. Python variables are
dynamically typed — you do not declare the type explicitly.

Variable Assignment
■ Variable Assignment
# Basic assignment
name = "Alice" # str
age = 30 # int
height = 5.7 # float
is_active = True # bool

# Multiple assignment
x = y = z = 0

# Tuple unpacking
a, b, c = 1, 2, 3

# Type checking
print(type(name)) # <class 'str'>
print(isinstance(age, int)) # True

Built-in Data Types


Type Category Example Mutable?

int Numeric 42, -7, 0 No

float Numeric 3.14, -0.5 No

complex Numeric 2+3j No

str Sequence 'hello' No

list Sequence [1, 2, 3] Yes

tuple Sequence (1, 2, 3) No

dict Mapping {'a': 1} Yes

set Set {1, 2, 3} Yes

frozenset Set frozenset({1,2}) No

bool Boolean True, False No

NoneType Null None No

bytes Binary b'hello' No

Strings in Detail
■ String Operations
s = "Hello, Python!"

# Indexing & Slicing


print(s[0]) # 'H'
print(s[-1]) # '!'
print(s[0:5]) # 'Hello'
print(s[::2]) # every 2nd character

# Methods
print([Link]()) # 'HELLO, PYTHON!'
print([Link]()) # 'hello, python!'
print([Link]('Python','World')) # 'Hello, World!'
print([Link](',')) # ['Hello', ' Python!']
print([Link]()) # removes leading/trailing spaces
print(len(s)) # 14

# f-strings (Python 3.6+)


name = "Alice"
age = 30
print(f"Name: {name}, Age: {age}") # 'Name: Alice, Age: 30'
print(f"Pi = {3.14159:.2f}") # 'Pi = 3.14'

# Multi-line strings
text = """Line 1
Line 2
Line 3"""

# String formatting
print("%-10s %5d" % ("item", 42)) # old style
print("{:>10} {:5d}".format("item", 42)) # new style

■ Common Mistake: Never use mutable objects (lists, dicts) as default argument values in functions.
■ Best Practice: Use f-strings for string formatting — they are the fastest and most readable option in Python
3.6+.

1.4 Operators
Category Operators Example

Arithmetic + - * / // % ** 10 // 3 = 3 (floor div)

Comparison == != > < >= <= 5 >= 3 → True

Logical and or not True and False → False

Bitwise & | ^ ~ << >> 5&3→1

Assignment = += -= *= /= //= **= x += 5

Identity is, is not x is None

Membership in, not in 'a' in 'cat' → True

■ Operator Examples
# Arithmetic
print(17 // 5) # 3 (floor division)
print(17 % 5) # 2 (modulus)
print(2 ** 10) # 1024 (exponentiation)

# Comparison returns bool


print(10 == 10) # True
print(10 != 5) # True

# Logical operators
x = 5
print(x > 0 and x < 10) # True
print(x < 0 or x == 5) # True
print(not x == 5) # False
# Chained comparison (Pythonic!)
print(0 < x < 10) # True

Summary — Chapter 1
Concept Key Points

Python Interpreted, dynamically typed, multi-paradigm

Variables No type declaration; assigned with =

Data Types int, float, str, list, tuple, dict, set, bool, None

Strings Immutable; rich methods; f-strings for formatting

Operators Arithmetic, comparison, logical, bitwise, identity, membership


Chapter 2: Control Flow

2.1 Conditionals
■ Definition: Conditional statements allow a program to choose different execution paths based on
Boolean expressions.
■ if / elif / else
score = 85

if score >= 90:


grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
else:
grade = 'F'

print(f"Grade: {grade}") # Grade: B

# One-liner (ternary expression)


label = "Pass" if score >= 60 else "Fail"
print(label) # Pass

# Nested conditions
x, y = 5, 10
if x > 0:
if y > 0:
print("Both positive")

■ Common Mistake: Python does NOT have a switch/case statement in versions < 3.10. Use if/elif chains or
dicts for dispatch tables.
■ Note: Python 3.10+ introduced 'match' (structural pattern matching).

2.2 Loops
for Loop
■ Definition: Iterates over any iterable (list, tuple, string, range, dict, etc.).
■ for Loop Examples
# Iterating a list
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)

# range() — most common


for i in range(5): # 0 1 2 3 4
print(i)

for i in range(2, 10, 2): # 2 4 6 8


print(i)

# enumerate — get index + value


for idx, val in enumerate(fruits, start=1):
print(f"{idx}. {val}")

# zip — iterate multiple lists


names = ['Alice', 'Bob']
scores = [95, 87]
for name, score in zip(names, scores):
print(f"{name}: {score}")

# Iterating dict
d = {'a': 1, 'b': 2}
for key, value in [Link]():
print(f"{key} -> {value}")

# Nested loops
for i in range(3):
for j in range(3):
print(f"({i},{j})", end=" ")
print()

while Loop
■ Definition: Repeats a block as long as a condition is True.
■ while Loop Examples
count = 0
while count < 5:
print(count)
count += 1

# Infinite loop with break


while True:
user_input = input("Enter 'quit' to exit: ")
if user_input == 'quit':
break
print(f"You entered: {user_input}")

# while with else


n = 0
while n < 3:
print(n)
n += 1
else:
print("Loop completed normally")

2.3 Break, Continue, Pass


■ Loop Control Statements
# break — exit the loop immediately
for i in range(10):
if i == 5:
break
print(i) # prints 0 1 2 3 4

# continue — skip current iteration


for i in range(10):
if i % 2 == 0:
continue
print(i) # prints 1 3 5 7 9

# pass — placeholder; does nothing


for i in range(5):
pass # empty loop (no error)

class MyClass:
pass # empty class definition

# for/else and while/else


for i in range(5):
if i == 10:
break
else:
print("No break occurred") # this runs

Statement Effect Use Case

break Exits loop entirely Found what we looked for

continue Skips to next iteration Skip unwanted values

pass Does nothing Placeholder for empty blocks


Chapter 3: Functions & Modules

3.1 Defining Functions


■ Definition: A function is a reusable, named block of code that performs a specific task. Functions
promote DRY (Don't Repeat Yourself) principle.
■ Function Basics
# Basic function
def greet(name):
"""Greet a person by name.""" # docstring
return f"Hello, {name}!"

print(greet("Alice")) # Hello, Alice!

# Function with default argument


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

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

# Multiple return values (returns a tuple)


def min_max(lst):
return min(lst), max(lst)

lo, hi = min_max([4, 1, 8, 2])


print(lo, hi) # 1 8

3.2 Arguments
■ Types of Arguments
# Positional
def add(a, b):
return a + b
add(3, 4) # a=3, b=4

# Keyword
add(b=4, a=3) # same result

# *args — variable positional


def total(*args):
return sum(args)
total(1, 2, 3, 4) # 10

# **kwargs — variable keyword


def show(**kwargs):
for k, v in [Link]():
print(f"{k}: {v}")
show(name="Alice", age=30)
# Positional-only (/) and keyword-only (*) — Python 3.8+
def strict(pos_only, /, normal, *, kw_only):
print(pos_only, normal, kw_only)
strict(1, 2, kw_only=3) # valid
strict(1, normal=2, kw_only=3) # also valid

3.3 Lambda Functions


■ Definition: A lambda is an anonymous, single-expression function. Syntax: lambda parameters:
expression
■ Lambda Functions
# Basic lambda
square = lambda x: x ** 2
print(square(5)) # 25

# With sorted()
students = [('Alice', 88), ('Bob', 95), ('Carol', 72)]
[Link](key=lambda s: s[1], reverse=True)
print(students) # [('Bob',95),('Alice',88),('Carol',72)]

# With map() and filter()


nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, nums))
doubled = list(map(lambda x: x * 2, nums))
print(evens) # [2, 4, 6]
print(doubled) # [2, 4, 6, 8, 10, 12]

■ Best Practice: Use lambda only for simple one-liners. For complex logic, define a regular function for
readability.

3.4 Modules & Packages


■ Definition: A module is a .py file containing Python code. A package is a directory containing multiple
modules and an __init__.py file.
■ Importing Modules
import math # import whole module
from math import sqrt, pi # import specific names
from math import sqrt as sq # alias
import os, sys # multiple modules

# Using the module


print([Link](5)) # 120
print(sqrt(16)) # 4.0
print(pi) # 3.141592...

# __name__ guard
if __name__ == '__main__':
print("Running as main script")
# code here runs only when script is executed directly

■ Creating a Module ([Link])


# [Link]
def celsius_to_fahrenheit(c):
return c * 9/5 + 32
def is_palindrome(s):
s = [Link]().replace(' ', '')
return s == s[::-1]

PI = 3.14159

# [Link]
from myutils import celsius_to_fahrenheit, is_palindrome
print(celsius_to_fahrenheit(100)) # 212.0
print(is_palindrome("racecar")) # True

Import Style Syntax When to Use

Full module import math When using multiple items from module

Specific name from math import sqrt When using one or few items

Alias import numpy as np Long module names; conventional aliases

All (avoid!) from math import * Avoid — pollutes namespace


Chapter 4: Data Structures

4.1 Lists
■ Definition: An ordered, mutable sequence. Allows duplicate elements. Elements can be of any type.
■ List Operations
# Creation
lst = [1, 2, 3, 4, 5]
mixed = [1, 'two', 3.0, True]
nested = [[1,2], [3,4]]

# Access
print(lst[0]) # 1
print(lst[-1]) # 5
print(lst[1:3]) # [2, 3]

# Modify
lst[0] = 10
[Link](6) # add to end
[Link](1, 99) # insert at index
[Link]([7, 8]) # merge another list

# Remove
[Link](99) # remove by value
popped = [Link]() # remove & return last
popped2 = [Link](0) # remove & return at index
del lst[0] # delete by index

# Search & Sort


print(5 in lst) # True
print([Link](3)) # index of value 3
[Link]() # in-place ascending
[Link](reverse=True) # in-place descending
sorted_lst = sorted(lst) # returns new sorted list
[Link]() # reverse in-place

# Other
print(len(lst))
[Link](2) # count occurrences
[Link]() # empty the list
copy = [Link]() # shallow copy

4.2 Tuples
■ Definition: An ordered, immutable sequence. Faster than lists. Used for fixed collections (coordinates,
RGB values, DB records).
■ Tuple Operations
t = (1, 2, 3)
single = (42,) # single-element tuple NEEDS trailing comma
empty = ()

# Access (same as list)


print(t[0]) # 1
print(t[1:]) # (2, 3)

# Unpacking
x, y, z = t
a, *rest = (1, 2, 3, 4, 5) # a=1, rest=[2,3,4,5]

# Named tuple — self-documenting


from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(p.x, p.y) # 3 4
print(p) # Point(x=3, y=4)

4.3 Dictionaries
■ Definition: An unordered (Python 3.7+ maintains insertion order) mapping of unique keys to values.
Keys must be immutable (str, int, tuple).
■ Dictionary Operations
# Creation
d = {'name': 'Alice', 'age': 30, 'city': 'NY'}
d2 = dict(name='Bob', age=25)

# Access
print(d['name']) # Alice
print([Link]('salary', 0)) # 0 (default if missing)

# Modify
d['age'] = 31 # update
d['email'] = 'a@[Link]' # add new key
[Link]({'city': 'LA', 'country': 'US'})

# Remove
del d['city']
val = [Link]('age') # remove & return
[Link]() # remove last inserted (3.7+)

# Iteration
for key in d:
print(key, d[key])
for k, v in [Link]():
print(f"{k}: {v}")
keys = list([Link]())
values = list([Link]())

# Dict comprehension
squares = {x: x**2 for x in range(1, 6)}
# {1:1, 2:4, 3:9, 4:16, 5:25}

# Merging dicts (Python 3.9+)


merged = d | d2 # union operator

# defaultdict — no KeyError on missing keys


from collections import defaultdict
word_count = defaultdict(int)
for word in "the cat sat on the mat".split():
word_count[word] += 1

4.4 Sets
■ Definition: An unordered collection of unique, immutable elements. Ideal for membership tests and
removing duplicates.
■ Set Operations
s1 = {1, 2, 3, 4}
s2 = {3, 4, 5, 6}

# Set operations
print(s1 | s2) # Union: {1,2,3,4,5,6}
print(s1 & s2) # Intersection: {3,4}
print(s1 - s2) # Difference: {1,2}
print(s1 ^ s2) # Symmetric diff: {1,2,5,6}

# Methods
[Link](5)
[Link](5) # raises KeyError if not found
[Link](99) # no error if not found

# Membership test — O(1)


print(3 in s1) # True

# Remove duplicates from list


lst = [1,2,2,3,3,3]
unique = list(set(lst)) # [1,2,3]

# frozenset — immutable set


fs = frozenset({1,2,3})

Structure Ordered Mutable Duplicates Key/Value Use Case

list Yes Yes Yes No General sequence

tuple Yes No Yes No Immutable records

dict Yes* Yes Keys: No Yes Key-value mapping

Unique items, math


set No Yes No No
ops
Chapter 5: Object-Oriented
Programming

5.1 Classes & Objects


■ Definition: A class is a blueprint for creating objects. An object is an instance of a class with its own
attributes (data) and methods (functions).
■ Class Basics
class Dog:
# Class attribute (shared by all instances)
species = "Canis familiaris"

# Constructor (initializer)
def __init__(self, name, age):
# Instance attributes
[Link] = name
[Link] = age

# Instance method
def bark(self):
return f"{[Link]} says: Woof!"

def __str__(self): # string representation


return f"Dog({[Link]}, {[Link]})"

def __repr__(self): # developer representation


return f"Dog(name={[Link]!r}, age={[Link]!r})"

# Create instances
dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)

print([Link]) # Buddy
print([Link]()) # Buddy says: Woof!
print([Link]) # Canis familiaris
print(dog1) # Dog(Buddy, 3)
print([Link]) # Canis familiaris

# Properties (controlled attribute access)


class Circle:
def __init__(self, radius):
self._radius = radius # convention: _ = private

@property
def radius(self):
return self._radius

@[Link]
def radius(self, value):
if value < 0:
raise ValueError("Radius cannot be negative")
self._radius = value

@property
def area(self):
import math
return [Link] * self._radius ** 2

c = Circle(5)
print([Link]) # 78.539...
[Link] = 10 # uses setter

5.2 Inheritance
■ Definition: Inheritance allows a class (child) to acquire attributes and methods of another class
(parent). Promotes code reuse.
■ Inheritance
class Animal:
def __init__(self, name, sound):
[Link] = name
[Link] = sound

def speak(self):
return f"{[Link]} says {[Link]}"

def __str__(self):
return f"{self.__class__.__name__}({[Link]})"

class Dog(Animal):
def __init__(self, name):
super().__init__(name, "Woof") # call parent __init__

def fetch(self, item):


return f"{[Link]} fetches the {item}!"

class Cat(Animal):
def __init__(self, name):
super().__init__(name, "Meow")

def purr(self):
return f"{[Link]} purrs..."

# Multiple inheritance
class Labrador(Dog):
breed = "Labrador"

d = Dog("Rex")
print([Link]()) # Rex says Woof
print([Link]("ball")) # Rex fetches the ball!
c = Cat("Whiskers")
print([Link]()) # Whiskers says Meow

# Check inheritance
print(isinstance(d, Dog)) # True
print(isinstance(d, Animal)) # True
print(issubclass(Dog, Animal)) # True

5.3 Polymorphism & Encapsulation


■ Polymorphism & Encapsulation
# Polymorphism — same interface, different behavior
class Shape:
def area(self): pass

class Rectangle(Shape):
def __init__(self, w, h):
self.w, self.h = w, h
def area(self):
return self.w * self.h

class Circle(Shape):
def __init__(self, r):
self.r = r
def area(self):
import math
return [Link] * self.r ** 2

shapes = [Rectangle(3,4), Circle(5)]


for s in shapes:
print(f"{s.__class__.__name__}: {[Link]():.2f}")
# Rectangle: 12.00
# Circle: 78.54

# Encapsulation — access control convention


class BankAccount:
def __init__(self, balance):
self.__balance = balance # name-mangled (private)

def deposit(self, amount):


if amount > 0:
self.__balance += amount

def withdraw(self, amount):


if 0 < amount <= self.__balance:
self.__balance -= amount
else:
raise ValueError("Insufficient funds")

@property
def balance(self):
return self.__balance

acc = BankAccount(1000)
[Link](500)
print([Link]) # 1500
# acc.__balance # AttributeError — protected!

Pillar Description Python Mechanism

Encapsulation Bundling data + methods; hiding internals _ and __ prefixes, @property

Inheritance Child class reuses parent class code class Child(Parent):

Polymorphism Same method name, different behavior Method overriding

Abstraction Hiding complex implementation Abstract Base Classes (abc module)


Chapter 6: File Handling

6.1 Reading & Writing Files


■ Definition: Python's built-in open() function is used to interact with files. Always use context managers
(with statement) to ensure files are properly closed.
■ File Operations
# Writing a file
with open('[Link]', 'w') as f:
[Link]("Line 1\n")
[Link]("Line 2\n")
[Link](["Line 3\n", "Line 4\n"])

# Reading entire file


with open('[Link]', 'r') as f:
content = [Link]() # entire file as string

# Reading line by line (memory-efficient)


with open('[Link]', 'r') as f:
for line in f:
print([Link]())

# Read all lines into list


with open('[Link]', 'r') as f:
lines = [Link]()

# Append to file
with open('[Link]', 'a') as f:
[Link]("Line 5\n")

# File modes: r(read), w(write), a(append),


# r+(read+write), b(binary), x(exclusive create)

6.2 CSV & JSON Files


■ CSV and JSON
import csv
import json

# Write CSV
data = [['Name','Age','City'],['Alice',30,'NY'],['Bob',25,'LA']]
with open('[Link]', 'w', newline='') as f:
writer = [Link](f)
[Link](data)

# Read CSV
with open('[Link]', 'r') as f:
reader = [Link](f)
for row in reader:
print(row['Name'], row['Age'])
# Write JSON
config = {'host':'localhost', 'port':5432, 'debug':True}
with open('[Link]', 'w') as f:
[Link](config, f, indent=4)

# Read JSON
with open('[Link]', 'r') as f:
loaded = [Link](f)
print(loaded['port']) # 5432

# JSON ↔ string
json_str = [Link](config, indent=2)
parsed = [Link](json_str)

Chapter 7: Exception Handling

7.1 try / except / finally


■ Definition: Exception handling allows a program to respond to runtime errors gracefully instead of
crashing. Python uses a try/except block.
■ Exception Handling
# Basic structure
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")

# Multiple exceptions
try:
x = int(input("Enter a number: "))
result = 100 / x
except ValueError:
print("Not a valid integer")
except ZeroDivisionError:
print("Cannot divide by zero")
except Exception as e: # catch-all
print(f"Unexpected error: {e}")
else:
print(f"Result: {result}") # runs if no exception
finally:
print("This always runs") # cleanup code

# Common exceptions
# ValueError — wrong type/value
# TypeError — wrong type
# IndexError — list index out of range
# KeyError — dict key not found
# FileNotFoundError — file missing
# AttributeError — object has no attribute
# NameError — variable not defined
7.2 Custom Exceptions
■ Custom Exception Classes
class ValidationError(Exception):
"""Raised when input validation fails."""
def __init__(self, message, field=None):
super().__init__(message)
[Link] = field

class InsufficientFundsError(Exception):
def __init__(self, balance, amount):
[Link] = balance
[Link] = amount
super().__init__(
f"Cannot withdraw {amount}. Balance: {balance}"
)

# Using custom exceptions


def process_age(age):
if not isinstance(age, int):
raise ValidationError("Age must be an integer", "age")
if age < 0 or age > 150:
raise ValidationError("Age out of range", "age")
return age

try:
process_age(-5)
except ValidationError as e:
print(f"Validation failed on field '{[Link]}': {e}")

# re-raising exceptions
try:
risky_operation()
except Exception as e:
print(f"Logging: {e}")
raise # re-raise the same exception
Chapter 8: Libraries — NumPy &
Pandas

8.1 NumPy
■ Definition: NumPy (Numerical Python) is the foundation for numerical computing in Python. It
provides the ndarray — an efficient N-dimensional array object.
■ NumPy Basics
import numpy as np

# Creating arrays
a = [Link]([1, 2, 3, 4, 5])
b = [Link]((3, 3)) # 3x3 zeros
c = [Link]((2, 4)) # 2x4 ones
d = [Link](0, 10, 2) # [0 2 4 6 8]
e = [Link](0, 1, 5) # [0. 0.25 0.5 0.75 1.]
r = [Link](3, 3) # 3x3 random [0,1)

# Shape & dtype


arr = [Link]([[1,2,3],[4,5,6]])
print([Link]) # (2, 3)
print([Link]) # 2
print([Link]) # int64
print([Link]) # 6

# Indexing & slicing


print(arr[0, 1]) # 2 (row 0, col 1)
print(arr[:, 1]) # [2 5] (all rows, col 1)
print(arr[1, :]) # [4 5 6]

# Operations (element-wise)
a = [Link]([1,2,3])
b = [Link]([4,5,6])
print(a + b) # [5 7 9]
print(a * b) # [4 10 18]
print(a ** 2) # [1 4 9]
print([Link](a)) # [1. 1.41 1.73]

# Matrix multiplication
A = [Link]([[1,2],[3,4]])
B = [Link]([[5,6],[7,8]])
print(A @ B) # [[19 22] [43 50]]
print([Link](A, B)) # same

# Statistical functions
data = [Link]([4,7,13,2,1])
print([Link](data)) # 5.4
print([Link](data)) # 4.03
print([Link](data)) # 1
print([Link](data)) # 13
print([Link](data)) # 27

# Reshaping
a = [Link](12)
b = [Link]((3, 4)) # 3 rows, 4 cols
c = [Link]() # back to 1D

8.2 Pandas
■ Definition: Pandas is the primary data analysis library for Python. Key structures: Series (1D) and
DataFrame (2D table).
■ Pandas Basics
import pandas as pd

# Creating a DataFrame
data = {
'Name': ['Alice','Bob','Carol','Dave'],
'Age': [25, 30, 35, 28],
'Salary': [50000, 65000, 80000, 55000],
'Dept': ['HR','IT','IT','Finance']
}
df = [Link](data)

# Basic inspection
print([Link](2)) # first 2 rows
print([Link](2)) # last 2 rows
print([Link]) # (4, 4)
print([Link]) # column types
print([Link]()) # statistics
print([Link]()) # memory, nulls

# Selecting data
print(df['Name']) # Series
print(df[['Name','Age']]) # DataFrame
print([Link][0]) # row by index
print([Link][0:2, 1:3]) # rows 0-1, cols 1-2
print([Link][0, 'Name']) # row label, col name

# Filtering
print(df[df['Age'] > 28])
print(df[df['Dept'] == 'IT'])
print(df[(df['Age'] > 25) & (df['Salary'] > 60000)])

# Adding columns
df['Tax'] = df['Salary'] * 0.2
df['Senior'] = df['Age'] >= 30

# GroupBy
grouped = [Link]('Dept')['Salary'].mean()
print(grouped)

# Sorting
df.sort_values('Salary', ascending=False, inplace=True)

# Handling missing values


df2 = [Link]()
[Link][0, 'Age'] = None
print([Link]().sum())
[Link](df2['Age'].mean(), inplace=True)
[Link](inplace=True)

# Reading/Writing
df.to_csv('[Link]', index=False)
df_loaded = pd.read_csv('[Link]')
df.to_excel('[Link]', index=False)
Chapter 9: APIs & Basic Automation

9.1 The requests Library


■ Definition: The requests library allows Python to make HTTP requests — fetching web pages, calling
REST APIs, submitting forms.
■ HTTP Requests
import requests
import json

# GET request
response = [Link]('[Link]
print(response.status_code) # 200
print([Link]()) # parsed JSON dict
print([Link]['Content-Type'])

# GET with params


params = {'q': 'python', 'sort': 'stars'}
r = [Link]('[Link]
params=params)
data = [Link]()
print(data['total_count'])

# POST request
payload = {'username': 'alice', 'password': 'secret'}
r = [Link]('[Link] json=payload)

# Headers & Authentication


headers = {'Authorization': 'Bearer YOUR_TOKEN'}
r = [Link]('[Link]
headers=headers)

# Error handling
try:
r = [Link]('[Link] timeout=5)
r.raise_for_status() # raises for 4xx/5xx
except [Link]:
print("Request timed out")
except [Link] as e:
print(f"HTTP error: {e}")

9.2 Basic Automation


■ File & OS Automation
import os
import shutil
from pathlib import Path

# Path operations (pathlib — modern approach)


p = Path('data') / 'reports' / '[Link]'
print([Link]) # [Link]
print([Link]) # q1
print([Link]) # .csv
print([Link]) # data/reports

# Create directories
Path('new_folder/sub').mkdir(parents=True, exist_ok=True)

# List files
for f in Path('.').glob('*.py'):
print(f)

for f in Path('.').rglob('*.csv'): # recursive


print(f)

# File info
f = Path('[Link]')
print([Link]())
print([Link]().st_size) # size in bytes

# Copy/move
[Link]('[Link]', '[Link]')
[Link]('old_name.txt', 'new_name.txt')

# Rename
Path('[Link]').rename('[Link]')

# Delete
Path('[Link]').unlink() # delete file
[Link]('folder') # delete directory

# Environment variables
import os
db_url = [Link]('DATABASE_URL', 'localhost')
Chapter 10: Advanced Topics

10.1 Comprehensions
■ List, Dict, Set Comprehensions
# List comprehension
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# With condition
evens = [x for x in range(20) if x % 2 == 0]

# Nested comprehension
matrix = [[i*j for j in range(1,4)] for i in range(1,4)]
# [[1,2,3],[2,4,6],[3,6,9]]

# Dict comprehension
word_len = {w: len(w) for w in ['hello','world','python']}
# {'hello':5, 'world':5, 'python':6}

# Set comprehension
unique_lengths = {len(w) for w in ['hello','hi','world']}
# {5, 2}

# Generator expression (lazy, memory-efficient)


gen = (x**2 for x in range(1000000))
print(next(gen)) # 0
print(sum(gen)) # computes lazily

10.2 Generators
■ Generator Functions
# Generator with yield
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b

fib = fibonacci()
for _ in range(10):
print(next(fib), end=' ')
# 0 1 1 2 3 5 8 13 21 34

# Finite generator
def countdown(n):
while n > 0:
yield n
n -= 1
for val in countdown(5):
print(val) # 5 4 3 2 1

# yield from (delegating to sub-generator)


def chain(*iterables):
for it in iterables:
yield from it

list(chain([1,2],[3,4],[5])) # [1,2,3,4,5]

10.3 Decorators
■ Definition: A decorator is a higher-order function that wraps another function to modify or extend its
behaviour.
■ Decorators
import time
from functools import wraps

# Basic decorator
def timer(func):
@wraps(func) # preserves original function metadata
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(n):
[Link](n)
return "Done"

slow_function(0.5) # slow_function took 0.5001s

# Decorator with arguments


def repeat(n):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
for _ in range(n):
result = func(*args, **kwargs)
return result
return wrapper
return decorator

@repeat(3)
def greet(name):
print(f"Hello {name}")

greet("Alice") # prints Hello Alice 3 times

# Built-in decorators
class MyClass:
count = 0

@classmethod
def get_count(cls):
return [Link]

@staticmethod
def validate(x):
return isinstance(x, int)

10.4 Context Managers


■ Context Managers
# Using with statement
with open('[Link]', 'r') as f:
data = [Link]() # f automatically closed

# Custom context manager using class


class Timer:
def __enter__(self):
import time
[Link] = [Link]()
return self

def __exit__(self, exc_type, exc_val, exc_tb):


[Link] = [Link]() - [Link]
print(f"Elapsed: {[Link]:.4f}s")
return False # don't suppress exceptions

with Timer() as t:
sum(range(1000000))

# Using contextlib
from contextlib import contextmanager

@contextmanager
def managed_resource(name):
print(f"Opening {name}")
try:
yield name
finally:
print(f"Closing {name}")

with managed_resource("database") as r:
print(f"Using {r}")
Chapter 11: Practice Questions

Beginner Level
Q1. Write a program that takes a number and prints whether it is even or odd.
Answer: n = int(input()); print('Even' if n%2==0 else 'Odd')

Q2. Write a function that returns the factorial of a number using recursion.
Answer: def fact(n): return 1 if n<=1 else n*fact(n-1)

Q3. Create a list of squares from 1 to 10 using a list comprehension.


Answer: squares = [x**2 for x in range(1,11)]

Q4. Given a string, count the frequency of each character.


Answer: from collections import Counter; Counter('hello')

Q5. Write a function to reverse a string without using built-in reverse.


Answer: def rev(s): return s[::-1]

Intermediate Level
Q6. Implement a stack class using a Python list with push, pop, peek, and is_empty methods.
Answer: class Stack: def __init__(self): [Link]=[] def push(self,x): [Link](x) def pop(self):
return [Link]() def peek(self): return [Link][-1] def is_empty(self): return len([Link])==0

Q7. Write a decorator that caches the results of function calls (memoization).
Answer: Use functools.lru_cache or implement a dict-based cache inside a closure.

Q8. Write a generator that produces prime numbers indefinitely.


Answer: Use a sieve or trial division with yield in a while True loop.

Q9. Parse a CSV file and compute the average of a numeric column.
Answer: Use [Link] and compute mean of the column values.

Q10. Write a context manager that suppresses a specific exception type.


Answer: Implement __enter__ and __exit__; return True in __exit__ to suppress.

Advanced Level
Q11. Implement a thread-safe singleton class in Python.
Answer: Use [Link] and double-checked locking in __new__ or __init__.

Q12. Create a custom iterator class that returns Fibonacci numbers up to N.


Answer: Implement __iter__ and __next__ with StopIteration when limit reached.

Q13. Use Pandas to: load a CSV, group by a category column, compute multiple aggregations, and
export the result.
Answer: [Link]('col').agg({'num':'mean','amt':'sum'}).reset_index().to_csv(...)
Q14. Write an async function that makes 3 API calls concurrently using asyncio.
Answer: Use [Link]() with [Link] for concurrent calls.

Q15. Implement the Observer pattern in Python using pure OOP.


Answer: Create Subject with register/unregister/notify, Observer with update method.
Chapter 12: Python Cheat Sheet

Data Types Quick Reference


Type Literal Key Methods/Ops

int 42, -7 +, -, *, //, %, **, abs(), bin(), hex()

float 3.14 round(), [Link](), [Link]()

str 'hi', "hi" .upper(),.lower(),.split(),.join(),.strip(),.format()

list [1,2,3] .append(),.extend(),.insert(),.remove(),.pop(),.sort()

dict {'k':1} .keys(),.values(),.items(),.get(),.update(),.pop()

set {1,2,3} .add(),.remove(),.union(),.intersection(),.difference()

tuple (1,2) indexing, unpacking, len(), in

bool True/False and, or, not, ==, !=

None None is None, is not None

Built-in Functions Quick Reference


Function Description Example

len(x) Length of sequence len([1,2,3]) → 3

range(s,e,step) Integer range range(0,10,2) → 0,2,4,6,8

enumerate(x) Index + value pairs for i,v in enumerate(lst)

zip(a,b) Pair elements for x,y in zip(lst1,lst2)

map(f,x) Apply func to each map(str, [1,2,3])

filter(f,x) Filter by func filter(lambda x:x>0, lst)

sorted(x) Return sorted copy sorted(lst, reverse=True)

sum(x) Sum iterable sum([1,2,3]) → 6

min/max(x) Min/max value min([3,1,2]) → 1

any/all(x) Logical tests any([False,True]) → True

isinstance(x,T) Type check isinstance(5, int) → True

type(x) Get type type(5) →

int/float/str/list(x) Type conversion int('42') → 42

print(*args) Output print('a','b', sep=',')


Function Description Example

input(prompt) User input (string) x = input('Enter: ')

open(file, mode) File handle open('[Link]','r')

hasattr(obj,name) Check attribute hasattr(obj,'run')

String Formatting
Style Syntax Example

f-string (3.6+) f"{var:.2f}" f"{pi:.4f}" → '3.1416'

.format() "{0} {1}".format(a,b) "{} {}".format(1,2) → '1 2'

% formatting "%s %d" % (s,n) "%s=%d" % ('x',5) → 'x=5'

OOP Quick Reference


Concept Syntax

Define class class MyClass:

Constructor def __init__(self, args):

Instance method def method(self):

Class method @classmethod def cm(cls):

Static method @staticmethod def sm():

Property @property def prop(self):

Inheritance class Child(Parent):

Super call super().__init__(args)

Abstract class from abc import ABC, abstractmethod

Dunder __str__ def __str__(self): return '...'

Exception Hierarchy (Partial)


■ Exception Tree
BaseException
■■■ SystemExit
■■■ KeyboardInterrupt
■■■ Exception
■■■ TypeError
■■■ ValueError
■■■ NameError
■■■ AttributeError
■■■ IndexError
■■■ KeyError
■■■ FileNotFoundError
■■■ OSError
■■■ ZeroDivisionError
■■■ StopIteration
■■■ RuntimeError

You might also like