Skip to content
Unit 5 Syllabus Note· Programming in Python

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 raises StopIteration when 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 inheriting unittest.TestCase, camelCase assertions.
  • pytest: Third-party, supports plain standalone functions, native Python assert statements, 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:

  1. __iter__(): Returns self.
  2. __next__(): Returns next element or raises StopIteration.
Python
1class FibonacciIterator:
2 """Generates Fibonacci numbers up to a maximum limit."""
3 def __init__(self, limit):
4 self.limit = limit
5 self.a = 0
6 self.b = 1
7 self.count = 0
8
9 def __iter__(self):
10 return self
11
12 def __next__(self):
13 if self.count >= self.limit:
14 raise StopIteration
15 val = self.a
16 self.a, self.b = self.b, self.a + self.b
17 self.count += 1
18 return val
19
20fib = FibonacciIterator(8)
21print("Fibonacci Sequence:", list(fib)) # [0, 1, 1, 2, 3, 5, 8, 13]

Generator Expressions vs List Comprehensions with Memory Comparisons

FeatureList ComprehensionGenerator Expression
Syntax[x**2 for x in range(n)](x**2 for x in range(n))
Type<class 'list'><class 'generator'>
EvaluationEager (allocates entire list at once)Lazy (computed only when consumed)
Memory ConsumptionO(n) proportional to sizeO(1) constant minimal overhead
ReusabilityCan be traversed repeatedlyOne-pass stream; exhausted after iteration

Web Scraping Workflow using requests and BeautifulSoup

Web Scraping 4-Stage Workflow

  1. Fetch: Send HTTP GET request via requests.get(url, headers={'User-Agent': '...'}).
  2. Parse: Parse HTML string into a searchable DOM tree: soup = BeautifulSoup(response.content, 'html.parser').
  3. Extract: Locate tags using CSS selectors or methods: soup.find(), soup.find_all('div', class_='...').
  4. 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() and tearDownClass() 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

Python
1"""
2MJPRU Examination Model Solution: Unit 5
3Ethical Web Scraper with Requests and BeautifulSoup
4"""
5import requests
6from bs4 import BeautifulSoup
7
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/5xx
19 except requests.RequestException as e:
20 print(f"Network error on page {page}: {e}")
21 break
22
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": tags
35 })
36
37 return scraped_data
38
39# Execution
40quotes = 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

Python
1import unittest
2
3# Class to be tested
4class Calculator:
5 def add(self, a, b):
6 return a + b
7
8 def divide(self, a, b):
9 if b == 0:
10 raise ZeroDivisionError("Division by zero is undefined!")
11 return a / b
12
13# Test Suite
14class 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 = None
22
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

Python
1import itertools
2
3# Infinite prime number generator
4def prime_generator():
5 yield 2
6 primes = [2]
7 candidate = 3
8 while True:
9 is_prime = True
10 limit = int(candidate ** 0.5) + 1
11 for p in primes:
12 if p > limit:
13 break
14 if candidate % p == 0:
15 is_prime = False
16 break
17 if is_prime:
18 primes.append(candidate)
19 yield candidate
20 candidate += 2
21
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.chain
28seq = 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.

Your reading progress
0%

100% left on this page — finishing it closes the gap for Iterators, Generators, Web Scraping & Testing.

Weak topic hint

Iterators, Generators, Web Scraping & Testing still counts as a weak topic until you finish this note and answer its questions.

Practise this unit
What Should You Do Next?

Test Your Understanding

Now that you've read through these notes, practice unit MCQs to identify weak points and solidify your learning before exams.