Programming in Python
Comprehensive exam revision notes for BCA-202N Unit 5 (Iterators, Generators, Web Scraping & Testing). Includes Section A (2M), Section B (5M), and Section C (15M) questions, answers, and diagrams.
Programming in Python
Iterators, Generators, Web Scraping & Testing
Core Definitions & Key Concepts
What is the difference between an Iterable and an Iterator in Python
- Iterable: Any object that implements
__iter__()and can return an iterator (e.g.,list,str,dict). - Iterator: A stateful object that implements
__next__()and raisesStopIterationwhen elements are exhausted.
What does the yield keyword do in Python
yield transforms a regular function into a generator. It suspends function execution, returns an intermediate value to the caller, and retains its local execution state to resume on next invocation.
What is the memory advantage of Generators over Lists
Lists store all elements in memory simultaneously (O(n) space). Generators produce values lazily on-demand one item at a time (O(1) space), enabling processing of infinite streams or gigabyte-sized log files.
What is itertools in Python
itertools is a standard library module providing fast, memory-efficient building blocks for iterator manipulation: e.g., count(), cycle(), permutations(), combinations(), chain().
What is Web Scraping, and which Python libraries are commonly used
Web scraping is the automated extraction of data from websites. Common Python libraries include requests (HTTP requests), BeautifulSoup (bs4 for parsing HTML DOM), and Selenium (browser automation).
What is the Robots.txt file in web scraping
A text file hosted at a website's root (e.g., example.com/robots.txt) specifying rules and directives (Allow/Disallow) for automated web crawlers and scraping bots.
What is the built-in testing framework in Python
unittest is Python's standard unit testing framework, patterned after Java's JUnit, providing test runners, test fixtures (setUp, tearDown), and assertions (assertEqual, assertTrue).
What is the difference between unittest and pytest
unittest: Built-in, requires boilerplate classes inheritingunittest.TestCase, camelCase assertions.pytest: Third-party, supports plain standalone functions, native Pythonassertstatements, and powerful fixture injection.
Conceptual & Architectural Analysis
How to Implement a Custom Iterator Class in Python with Code
Implementing the Iterator Protocol
An iterator class must implement:
__iter__(): Returnsself.__next__(): Returns next element or raisesStopIteration.
1class FibonacciIterator:2 """Generates Fibonacci numbers up to a maximum limit."""3 def __init__(self, limit):4 self.limit = limit5 self.a = 06 self.b = 17 self.count = 08 9 def __iter__(self):10 return self11 12 def __next__(self):13 if self.count >= self.limit:14 raise StopIteration15 val = self.a16 self.a, self.b = self.b, self.a + self.b17 self.count += 118 return val19
20fib = FibonacciIterator(8)21print("Fibonacci Sequence:", list(fib)) # [0, 1, 1, 2, 3, 5, 8, 13]Generator Expressions vs List Comprehensions with Memory Comparisons
| Feature | List Comprehension | Generator Expression |
|---|---|---|
| Syntax | [x**2 for x in range(n)] | (x**2 for x in range(n)) |
| Type | <class 'list'> | <class 'generator'> |
| Evaluation | Eager (allocates entire list at once) | Lazy (computed only when consumed) |
| Memory Consumption | O(n) proportional to size | O(1) constant minimal overhead |
| Reusability | Can be traversed repeatedly | One-pass stream; exhausted after iteration |
Web Scraping Workflow using requests and BeautifulSoup
Web Scraping 4-Stage Workflow
- Fetch: Send HTTP GET request via
requests.get(url, headers={'User-Agent': '...'}). - Parse: Parse HTML string into a searchable DOM tree:
soup = BeautifulSoup(response.content, 'html.parser'). - Extract: Locate tags using CSS selectors or methods:
soup.find(),soup.find_all('div', class_='...'). - Persist: Clean text (
.strip()) and store in CSV or JSON.
Test Fixtures (setUp and tearDown) in Python's unittest Framework
Test fixtures ensure reliable test environments:
setUp(): Executes before each test method to initialize resources (e.g., creating test data, connecting to mock database).tearDown(): Executes after each test method to release resources (e.g., closing file descriptors, clearing temporary tables).- Class-level fixtures:
setUpClass()andtearDownClass()run once for the entire test class.
In-Depth Analysis & Implementation
Develop a Complete HTML Web Scraper in Python using requests and BeautifulSoup with Error Handling
1"""2MJPRU Examination Model Solution: Unit 53Ethical Web Scraper with Requests and BeautifulSoup4"""5import requests6from bs4 import BeautifulSoup7
8def scrape_quotes(page_limit=1):9 base_url = "http://quotes.toscrape.com"10 headers = {"User-Agent": "AcademicResearcher/1.0 (MJPRU BCA Student Project)"}11 scraped_data = []12 13 for page in range(1, page_limit + 1):14 url = f"{base_url}/page/{page}/"15 print(f"Fetching URL: {url}...")16 try:17 resp = requests.get(url, headers=headers, timeout=10)18 resp.raise_for_status() # Raises HTTPError for 4xx/5xx19 except requests.RequestException as e:20 print(f"Network error on page {page}: {e}")21 break22 23 soup = BeautifulSoup(resp.text, "html.parser")24 quote_boxes = soup.find_all("div", class_="quote")25 26 for box in quote_boxes:27 text = box.find("span", class_="text").get_text(strip=True)28 author = box.find("small", class_="author").get_text(strip=True)29 tags = [t.get_text() for t in box.find_all("a", class_="tag")]30 31 scraped_data.append({32 "quote": text,33 "author": author,34 "tags": tags35 })36 37 return scraped_data38
39# Execution40quotes = scrape_quotes(page_limit=1)41print(f"\nExtracted {len(quotes)} quotes successfully:")42for q in quotes[:3]:43 print(f"- \"{q['quote'][:40]}...\" by {q['author']} (Tags: {', '.join(q['tags'])})")Write a Complete Unit Test Suite using Python's unittest Library Testing a Calculator Class
1import unittest2
3# Class to be tested4class Calculator:5 def add(self, a, b):6 return a + b7 8 def divide(self, a, b):9 if b == 0:10 raise ZeroDivisionError("Division by zero is undefined!")11 return a / b12
13# Test Suite14class TestCalculator(unittest.TestCase):15 def setUp(self):16 """Runs before every test method."""17 self.calc = Calculator()18 19 def tearDown(self):20 """Runs after every test method."""21 self.calc = None22 23 def test_addition(self):24 self.assertEqual(self.calc.add(10, 5), 15)25 self.assertEqual(self.calc.add(-1, 1), 0)26 27 def test_division(self):28 self.assertAlmostEqual(self.calc.divide(10, 3), 3.3333333, places=5)29 30 def test_division_by_zero_exception(self):31 """Verify that ZeroDivisionError is raised."""32 with self.assertRaises(ZeroDivisionError):33 self.calc.divide(10, 0)34
35if __name__ == "__main__":36 unittest.main()Demonstrate Advanced Infinite Stream Processing using Python Generators and itertools
1import itertools2
3# Infinite prime number generator4def prime_generator():5 yield 26 primes = [2]7 candidate = 38 while True:9 is_prime = True10 limit = int(candidate ** 0.5) + 111 for p in primes:12 if p > limit:13 break14 if candidate % p == 0:15 is_prime = False16 break17 if is_prime:18 primes.append(candidate)19 yield candidate20 candidate += 221
22# Consuming infinite generator using itertools.islice (O(1) memory)23first_10_primes = list(itertools.islice(prime_generator(), 10))24print("First 10 Prime Numbers:", first_10_primes)25# Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]26
27# Demonstrating itertools.chain28seq = list(itertools.chain([1, 2], ['a', 'b'], [10.5, 20.5]))29print("Chained Iterables:", seq)Important Exam Points & Quick Revision
Be prepared to write custom iterators with __iter__ and __next__, explain generator memory efficiency, and show unittest.TestCase structure.
100% left on this page — finishing it closes the gap for Iterators, Generators, Web Scraping & Testing.
Iterators, Generators, Web Scraping & Testing still counts as a weak topic until you finish this note and answer its questions.
Practise this unitTest Your Understanding
Now that you've read through these notes, practice unit MCQs to identify weak points and solidify your learning before exams.