←Back to Subject
Notes
Notes
Study material and explanations
Diagrams
Diagrams
Visualize concepts easily
Mnemonics
Mnemonics
Tricks to remember faster
One Night Prep
One Night Prep
Short and focused revision
Revision
Revision
Quick summary and key points
Important Questions
Important Questions
Practice most relevant questions
Revision

Python Programming · Unit 2 Revision

Quick summary and key points for Unit 2

Control Statements in Python: Conditional & Loop Statements

Overview: Use if and elif for mutually exclusive grade bands and test the highest threshold first.

Conditional Control Statements (Decision Making)

  • Conditional statements check a boolean condition (True or False) and execute a specific block of code based on the result.
  • A. Simple if Statement: Executes a block of code only if the given condition is True.
  • B. if-else Statement: Provides two paths: if the condition is True, the if block runs; otherwise (False), the else block runs.
  • C. if-elif-else Ladder: Used when you need to check multiple conditions one after another.
  • D. Nested if Statement: Writing an if or if-else statement inside another if statement is called a Nested if.

View diagram · Execution Flow of if-elif-else

Loop Control Statements (Iteration)

  • Loops are used to execute a block of statements repeatedly until a condition is met or a sequence finishes.
  • A. The for Loop: In Python, the for loop is used to iterate over a sequence (such as a list, tuple, string, set, dictionary, or…
  • Role of the range() Function: range(start, stop, step) generates a sequence of integers:
  • range(5) → 0, 1, 2, 3, 4 (starts at 0, stops before 5)
  • range(1, 6) → 1, 2, 3, 4, 5
  • range(2, 11, 2) → 2, 4, 6, 8, 10 (step of 2)
  • B. The while Loop: The while loop repeats a block of code as long as a boolean condition remains True.
  • When to use: When the number of iterations is known (iterating over a sequence)

Jump / Loop Control Keywords (break, continue, pass)

  • break Statement: Immediately terminates the loop and transfers control outside the loop.
  • continue Statement: Skips the remaining statements of the current iteration and jumps to the next iteration of the loop.
  • pass Statement: A null (empty) statement in Python.

Data Structures & Collections: String, List, and Tuple

Overview: For the string PYTHON, index -1 gives N and slice 1:4 gives YTH because the stop position is excluded.

String (str) in Python

  • A String is an ordered, immutable sequence of Unicode characters enclosed within single quotes ('...'), double quotes ("..."), or…
  • Key Properties of Strings: Ordered: Characters maintain their insertion order and can be accessed via index.
  • Immutable (Cannot be changed in-place): Once a string is created, you cannot modify a single character like s[0] = 'J'.
  • String Slicing (string[start : stop : step]): Extracts a substring starting at start up to stop - 1.
  • s.upper(): Converts all characters to uppercase
  • s.lower(): Converts all characters to lowercase
  • s.title(): Capitalizes first letter of each word
  • s.strip(): Removes leading and trailing spaces

List (list) in Python

  • A List is an ordered, mutable (changeable) collection of elements enclosed in square brackets [ ].
  • Key Properties of Lists: Ordered: Maintains element order (0-based indexing).
  • Mutable: You can add, modify, or remove elements after creation.
  • Allows Duplicates: Same value can appear multiple times.
  • Heterogeneous: Can store [101, "Rahul", 85.5, True].
  • L.append(x): Adds single element x at the end of the list
  • L.insert(i, x): Inserts x at specific index i
  • L.extend(seq): Adds multiple elements from another sequence

Tuple (tuple) in Python

  • A Tuple is an ordered, immutable (unchangeable) collection of elements enclosed in parentheses ( ).
  • Key Properties of Tuples: Immutable: Once created, elements cannot be added, modified, or deleted.
  • Faster & Safer than Lists: Because tuples are read-only, Python allocates fixed memory for them, making them faster than lists and ideal for storing…
  • Can be used as Dictionary Keys: Unlike lists, tuples are hashable and can be used as keys in a Python dictionary.
  • Exam Tip — Single Element Tuple: To create a tuple with only one element, you must include a trailing comma: t = (10,).
  • Built-in Tuple Methods & Functions: Because tuples cannot be modified, they only have two built-in methods (count() and index()), along with universal…
  • t.count(x) — Returns how many times x appears in the tuple.
  • t.index(x) — Returns the index of the first occurrence of x.

Python Sets, Dictionaries & Comparison of List, Tuple, and Set

Overview: Two attendance entries for roll 17 collapse into one value in a set.

Set (set) in Python

  • A Set is an unordered, unindexed, and mutable collection of unique elements enclosed in curly braces { }.
  • Key Properties of Sets: No Duplicate Elements: Sets automatically remove duplicate values.
  • Unordered & Unindexed: Elements do not have a fixed position, so you cannot access items using indexes like s[0].
  • Mutable: You can add or remove items from a set using .add() and .remove().
  • Exam Trap — Empty Set Creation: Writing s = {} creates an empty Dictionary, NOT an empty Set!
  • Mathematical Set Operations in Python: Union collects distinct members from either set and intersection keeps shared members.

View diagram · Mathematical Set Operations (Let A = {1, 2, 3} and B = {3, 4, 5})

Dictionary (dict) in Python

  • A Dictionary is a mutable collection that stores data in key : value pairs enclosed within curly braces { }.
  • Key Properties of Dictionaries: Key-Value Mapping: Instead of numeric indexes (0, 1, 2), items are accessed via their Key.
  • Unique & Immutable Keys: Keys must be unique and immutable (strings, numbers, or tuples).
  • Mutable Values: Values can be of any data type, can be duplicated, and can be modified anytime.
  • d.keys(): Returns a view of all keys in the dictionary
  • d.values(): Returns a view of all values in the dictionary
  • d.items(): Returns a list-like view of (key, value) tuples
  • d.get(key, default): Returns value for key without throwing KeyError if missing

Comparison of List, Tuple, Set, and Dictionary

  • This comparison table is one of the most frequently asked questions in DAVV BCA exams:
  • Syntax / Brackets: Square brackets [ ]
  • Example: [10, 20, 30]
  • Mutability: Mutable (Changeable)
  • Ordering: Ordered
  • Indexing / Slicing: Supported (L[0])
  • Duplicate Elements: Allowed

Functions in Python: Types, Lambda, map(), filter() & reduce()

Overview: For marks 40, 55 and 70, map can add five to each mark, filter can keep only marks above 50, and reduce can combine them into one total.

Defining and Calling a Function

  • In Python, a function is defined using the def keyword followed by the function name, parentheses ( ), and a colon (:).

Types of Functions in Python

  • A built-in function is supplied by Python and a user-defined function is written with def.
  • Types of Function Arguments in Python: Positional Arguments: Passed in the exact order of parameters (add(10, 20)).
  • Keyword Arguments: Passed using parameter names (student(name="Riya", roll=101)), so order doesn’t matter.
  • Default Arguments: Parameters given a default value (def greet(name="Guest"):).
  • Variable-Length Arguments:
  • *args: Accepts any number of positional arguments as a Tuple.
  • **kwargs: Accepts any number of keyword arguments as a Dictionary.

View diagram · Types of Functions in Python

Lambda Function (Anonymous Function)

  • A Lambda Function is a small, anonymous (nameless) function defined using the lambda keyword instead of def.
  • It can take any number of arguments, but can have only one expression.
  • The result of the expression is automatically returned (no return keyword needed).
  • Keyword: Defined using def
  • Function Name: Must have a name
  • Number of Lines: Can have multiple lines & statements
  • Return Statement: Requires explicit return

Functional Programming Tools: map(), filter(), and reduce()

  • Python provides three classic higher-order functions that take a function (often a lambda) and a sequence as arguments.
  • A. The map() Function: Applies a given function to every item of an iterable (like a list) and returns a new mapped collection.
  • B. The filter() Function: Filters elements from a sequence by testing each item with a function that returns True or False.
  • C. The reduce() Function: Applies a rolling computation to sequential pairs of values in a list and reduces the entire list down to a **single cumulative…
  • Available in the built-in functools module (from functools import reduce).

View diagram · How map(), filter(), and reduce() Work on [1, 2, 3, 4]