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 (
TrueorFalse) 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, theifblock runs; otherwise (False), theelseblock runs. - C. if-elif-else Ladder: Used when you need to check multiple conditions one after another.
- D. Nested if Statement: Writing an
iforif-elsestatement inside anotherifstatement is called a Nestedif.
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
forloop is used to iterate over a sequence (such as alist,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 at0, stops before5)range(1, 6)→1, 2, 3, 4, 5range(2, 11, 2)→2, 4, 6, 8, 10(step of2)- B. The while Loop: The
whileloop repeats a block of code as long as a boolean condition remainsTrue. - When to use: When the number of iterations is known (iterating over a sequence)
Jump / Loop Control Keywords (break, continue, pass)
breakStatement: Immediately terminates the loop and transfers control outside the loop.continueStatement: Skips the remaining statements of the current iteration and jumps to the next iteration of the loop.passStatement: 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 atstartup tostop - 1. s.upper(): Converts all characters to uppercases.lower(): Converts all characters to lowercases.title(): Capitalizes first letter of each words.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 elementxat the end of the listL.insert(i, x): Insertsxat specific indexiL.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()andindex()), along with universal… t.count(x)— Returns how many timesxappears in the tuple.t.index(x)— Returns the index of the first occurrence ofx.
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 : valuepairs 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 dictionaryd.values(): Returns a view of all values in the dictionaryd.items(): Returns a list-like view of(key, value)tuplesd.get(key, default): Returns value forkeywithout throwingKeyErrorif 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
defkeyword 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
lambdakeyword instead ofdef. - It can take any number of arguments, but can have only one expression.
- The result of the expression is automatically returned (no
returnkeyword 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
TrueorFalse. - 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
functoolsmodule (from functools import reduce).
View diagram · How map(), filter(), and reduce() Work on [1, 2, 3, 4]