Prerequisite : Programming Basics

Read the notes, watch the video & take the MCQ test »

Answer : A program is a set of step-by-step instructions, written in a programming language, that tells a computer how to perform a task. It typically takes input, processes it and produces output.

Answer : An algorithm is a finite, ordered sequence of well-defined steps that solves a problem. Its properties are input, output, definiteness (each step is clear), finiteness (it always ends) and effectiveness (each step can actually be carried out).

Answer : An algorithm is the logical, language-independent solution to a problem, usually written in plain steps. A program is the implementation of an algorithm in a specific programming language so that a computer can execute it.

Answer : A flowchart is a diagram that represents an algorithm using standard symbols connected by arrows. It makes the flow of logic easy to see, which helps in planning, explaining and debugging a solution before coding.

Answer : Start/Stop: oval (terminal). Input/Output: parallelogram. Process: rectangle. Decision: diamond.

Answer : Pseudocode is an informal, structured description of an algorithm written in plain English with programming-like keywords such as IF, ELSE and WHILE. It has no strict syntax and is used to plan logic before writing real code.

Answer : Low-level languages (machine code, assembly) are close to the hardware and hard for humans to read. High-level languages (Python, Java, C++) use English-like syntax, are easier to write and maintain, and are translated into machine instructions by a compiler or interpreter.

Answer : A compiler translates the entire program into machine code before execution and usually creates an executable file. An interpreter translates and executes the program statement by statement, stopping at the first error it reaches while running.

Answer : The standard implementation, CPython, compiles source code into bytecode and then interprets the bytecode in the Python Virtual Machine. Because programs run directly from source without a separate build step, Python is generally called an interpreted language.

Answer : A syntax error occurs when code breaks the grammar rules of the language, so the program cannot start. Example: print("Hello" – the closing bracket is missing.

Answer : A runtime error (exception) occurs while a syntactically valid program is running. Example: 10 / 0 raises ZeroDivisionError.

Answer : A logical error is a mistake in the program’s logic that produces a wrong result without any error message, for example using + instead of * to calculate an area. It is hard to detect because the program runs normally; it is found only by testing outputs.

Answer : Every program receives data (input), performs operations on it (process) and presents results (output). For example, a billing program reads item prices, calculates the total with tax and prints the bill.

Answer : Planning separates problem solving from language details, helps find logical mistakes early, makes the solution easier to explain to others and reduces debugging time later.

Answer : 1. Start. 2. Read number N. 3. If N modulo 2 equals 0, display "Even"; otherwise display "Odd". 4. Stop.
MCQ Answer Key
No.QuestionCorrect Answer
1Which flowchart symbol represents a decision?C. Diamond
2Which property says an algorithm must always end after a finite number of steps?A. Finiteness
3In CPython, source code is first converted into:B. Bytecode
4A program runs without any error message but prints the wrong answer. This is a:D. Logical error
5Which statement about a compiler is TRUE?C. It translates the whole program before execution
Chapter-1 | Google Colab and Python Basics

Read the notes, watch the video & take the MCQ test »

Answer : Python was created by Guido van Rossum and first released in 1991. Python 3, the current version line, was released in 2008.

Answer : Easy-to-read syntax using indentation, interpreted execution, dynamic typing, automatic memory management (garbage collection), support for multiple paradigms (procedural, object-oriented, functional), and a large standard library with many third-party packages.

Answer : A variable’s type is decided at run time from the value assigned to it; you do not declare types in advance. The same name can later refer to a value of a different type.

Answer : Google Colab is a free, cloud-hosted Jupyter notebook environment. It requires no installation, includes popular libraries such as NumPy and pandas, saves notebooks to Google Drive and makes sharing easy.

Answer : A code cell contains Python code that can be executed, and its output is shown below it. A text cell contains formatted notes written in Markdown and is not executed as code.

Answer : The runtime is the running Python process that executes the notebook’s code cells and keeps their variables in memory. Restarting it clears all variables and imports, so cells must be run again.

Answer : sep is the string inserted between multiple values (default is a single space). end is the string printed after the last value (default is a newline). For example print("A","B",sep="-") prints A-B.

Answer : A single-line comment begins with #, and everything after # on that line is ignored. Docstrings – string literals placed as the first statement of a module, function or class – are used for documentation.

Answer : Python uses indentation to define blocks of code, such as the body of if statements, loops and functions. Statements in the same block must be indented equally; incorrect indentation causes an IndentationError or changes the program’s meaning.

Answer : PEP 8, the official style guide for Python code, recommends 4 spaces per indentation level.

Answer : Keywords are reserved words with special meaning in Python that cannot be used as identifiers. Examples: if, else, for, def and return (also True, False, None, while, import).

Answer : An identifier may contain letters, digits and underscores; it cannot start with a digit; it cannot be a keyword; it cannot contain spaces or special symbols; and names are case-sensitive.

Answer : Yes. Names that differ only in letter case are different identifiers. For example, Total = 10 and total = 20 create two separate variables.

Answer : Import the keyword module and call keyword.iskeyword("word"), which returns True for keywords. keyword.kwlist gives the full list of keywords.

Answer : It displays: Python 3 is fun – the three values are separated by the default separator, a single space.
MCQ Answer Key
No.QuestionCorrect Answer
1Python was created by:B. Guido van Rossum
2What is the output of print("A", "B", sep="-")?C. A-B
3Which of these is a VALID identifier?A. _total1
4Which keyboard shortcut runs the current cell in Google Colab?D. Shift + Enter
5Which symbol begins a single-line comment in Python?B. #
Chapter-2 | Variables and Data Types

Read the notes, watch the video & take the MCQ test »

Answer : A variable is a name that refers to an object (value) stored in memory. It is created automatically when a value is first assigned to it with the = operator; no type declaration is needed.

Answer : In C a variable must be declared with a type before use (int x;). In Python a variable is created simply by assigning a value (x = 10), and its type comes from the value.

Answer : int for whole numbers (25, -7), float for decimal numbers (3.14, 2.5e3) and complex for complex numbers (2 + 3j).

Answer : type() returns the class (data type) of the object passed to it, for example type(3.14) returns <class 'float'>.

Answer : type(x) returns the exact class of x. isinstance(x, T) returns True if x is an instance of T or of a subclass of T, which makes it the preferred way to test types in programs. For example isinstance(True, int) is True because bool is a subclass of int.

Answer : None is a special constant that represents the absence of a value. Its type is NoneType. Functions that do not return anything explicitly return None.

Answer : Several variables can be assigned in one statement: x, y, z = 10, 20, 30 assigns each value to the corresponding name, and a = b = c = 0 assigns the same value to all three names.

Answer : Using tuple packing and unpacking: x, y = y, x. No temporary variable is needed.

Answer : Mutable objects can be changed in place after creation – list, dict and set. Immutable objects cannot be changed – int, float, str, bool and tuple; any “change” creates a new object.

Answer : Strings are immutable, so their characters cannot be replaced. Python raises TypeError: 'str' object does not support item assignment. A new string must be created instead.

Answer : id() returns an integer that uniquely identifies an object during its lifetime (its identity). If a mutable object is modified in place, its id stays the same.

Answer : The type is associated with the value, not the variable, and is checked at run time. Example: value = 100 (int) and later value = "one hundred" (str) – the same name now refers to a string.

Answer : No fixed limit. Python int has arbitrary precision and can grow as large as available memory allows.

Answer : Lowercase words separated by underscores (snake_case), for example total_marks or student_name.

Answer : Sequence types store ordered items accessed by position – str, list, tuple and range. A mapping type stores key–value pairs – dict.
MCQ Answer Key
No.QuestionCorrect Answer
1What is the output of print(type(3.0))?B. <class 'float'>
2Which of the following data types is MUTABLE?D. list
3After x, y = 5, 9 and then x, y = y, x, what is the value of x?A. 9
4What is the type of None?C. NoneType
5What does isinstance(True, int) return?B. True
Chapter-3 | Basic Operators

Read the notes, watch the video & take the MCQ test »

Answer : / performs true division and always returns a float (10 / 2 gives 5.0). // performs floor division and returns the largest whole number less than or equal to the result (17 // 5 gives 3).

Answer : -4. Floor division rounds towards minus infinity, and -3.4 rounded down is -4, not -3.

Answer : % returns the remainder of division. 17 % 5 is 2. -17 % 5 is 3, because in Python the remainder takes the sign of the divisor and (a // b) * b + a % b always equals a.

Answer : It returns a tuple (a // b, a % b), the quotient and remainder together. divmod(17, 5) returns (3, 2).

Answer : == (equal), != (not equal), > (greater than), < (less than), >= (greater than or equal to) and <= (less than or equal to). They return True or False.

Answer : Python allows multiple comparisons in one expression, such as 10 < x < 20, which means 10 < x and x < 20.

Answer : For and, if the first operand is false Python stops and returns it without evaluating the second. For or, if the first operand is true Python stops and returns it. Hence 0 or "default" returns "default" and 5 and 10 returns 10.

Answer : They combine an operation with assignment: x += 5 means x = x + 5. Others include -=, *=, /=, //=, %= and **=.

Answer : No. Python has no increment or decrement operators; use x += 1 or x -= 1 instead.

Answer : 12 is 1100 and 10 is 1010 in binary. 12 & 10 = 1000 = 8, 12 | 10 = 1110 = 14, and 12 ^ 10 = 0110 = 6.

Answer : << shifts bits to the left (each shift multiplies by 2); >> shifts bits to the right (each shift floor-divides by 2). 12 << 1 is 24 and 12 >> 2 is 3.

Answer : in and not in test whether a value is present in a sequence or collection. "y" in "Python" is True and 4 not in [1, 2, 3] is True.

Answer : == checks whether two objects have equal values. is checks whether two names refer to the same object in memory. Two separate lists [1, 2] are == but not is.

Answer : The exponent operator is right-associative, so it is evaluated as 2 ** (3 ** 2) = 2 ** 9 = 512.

Answer : Multiplication has higher precedence than addition, so 2 + 3 * 4 = 2 + 12 = 14. Parentheses are evaluated first, so (2 + 3) * 4 = 5 * 4 = 20.
MCQ Answer Key
No.QuestionCorrect Answer
1What is the output of print(7 // 2)?C. 3
2What is the output of print(2 ** 3 ** 2)?B. 512
3Which operator checks whether two names refer to the SAME object?A. is
4What does print(0 or "default") display?D. default
5What is the result of 10 / 2 in Python 3?B. 5.0
Chapter-4 | Data Reading (Input) and Type Casting

Read the notes, watch the video & take the MCQ test »

Answer : input() always returns the text typed by the user as a string (str), even if the user types digits. It must be converted to a number before arithmetic.

Answer : Both values are strings, and + on strings performs concatenation (joining), not numeric addition. Converting them first, int("10") + int("20"), gives 30.

Answer : x, y = map(int, input().split()). split() breaks the text into parts at whitespace, and map(int, ...) converts each part to an integer.

Answer : Type casting (explicit type conversion) is converting a value from one data type to another using built-in functions such as int(), float(), str(), bool(), list() or tuple().

Answer : Implicit conversion is done automatically by Python, for example int + float produces a float. Explicit conversion is done by the programmer using functions such as int("5").

Answer : int() truncates towards zero, so int(7.9) is 7 and int(-7.9) is -7. It does not round to the nearest whole number.

Answer : Zero numbers (0, 0.0), empty strings (""), empty collections ([], (), {}, set()) and None are False. Everything else, including the string "0", is True.

Answer : Python does not implicitly convert between strings and numbers. Adding a str and an int raises TypeError: can only concatenate str (not "int") to str. Convert explicitly with str(3) or int("5").

Answer : ValueError is raised because "abc" is not a valid integer. It can be handled with try: n = int(text) except ValueError: print("Invalid number").

Answer : ord() returns the Unicode code point of a single character, e.g. ord("A") is 65. chr() returns the character for a code point, e.g. chr(97) is "a".

Answer : Pass the base as the second argument to int(): int("1010", 2) gives 10 and int("ff", 16) gives 255.

Answer : An f-string (formatted string literal, introduced in Python 3.6) is a string prefixed with f in which expressions inside curly braces are evaluated and inserted, for example f"Total: {price * qty}".

Answer : Use the format specifier .2f, for example f"{percent:.2f}" displays 87.4 as 87.40.

Answer : 4. bool is a subclass of int, and True behaves as the integer 1 in arithmetic.

Answer : Use list("abc"), which returns ['a', 'b', 'c'].
MCQ Answer Key
No.QuestionCorrect Answer
1What is the data type of the value returned by input()?D. str
2What is the output of print(int(9.99))?A. 9
3What does bool("0") return?B. True
4Which exception is raised by int("12a")?C. ValueError
5What does f"{3.14159:.2f}" produce?D. 3.14
Chapter-5 | Decision Making

Read the notes, watch the video & take the MCQ test »

Answer : They are statements that execute different blocks of code depending on whether a condition is True or False. In Python they are if, if-else, if-elif-else, nested if and the match statement.

Answer : if condition: (indented statements run when the condition is True) else: (indented statements run when it is False). Each header line ends with a colon and the blocks are defined by indentation.

Answer : Conditions are tested from top to bottom. The block of the first condition that is True is executed and the rest are skipped. If none is True, the else block (if present) runs.

Answer : A nested if is an if statement placed inside another if or else block. It is used when a second decision depends on the result of the first.

Answer : (year % 4 == 0 and year % 100 != 0) or year % 400 == 0. A year divisible by 4 is a leap year unless it is divisible by 100, except that years divisible by 400 are leap years.

Answer : It chooses between two values in one expression: value_if_true if condition else value_if_false. Example: larger = a if a > b else b.

Answer : Falsy values are treated as False in a condition: False, None, 0, 0.0, empty string and empty collections. All other values are truthy and are treated as True.

Answer : = is assignment, which is a statement and not allowed as a condition. Python raises a SyntaxError. Use == to compare: if x == 5:.

Answer : No. else is optional; an if (or if-elif chain) can exist without it, in which case nothing happens when all conditions are False.

Answer : match is the structural pattern-matching statement introduced in Python 3.10. It compares a subject value against case patterns and runs the first matching block, similar to switch-case in other languages.

Answer : _ is the wildcard pattern. It matches any value and is used as the default case when no other pattern matches.

Answer : Combine patterns with |, for example case "Saturday" | "Sunday": matches either string.

Answer : pass is a placeholder that does nothing. It is used when a block is syntactically required but no action is needed yet.

Answer : and, or and not combine or invert conditions so that a single if can test several requirements, for example if age >= 18 and has_id:.

Answer : if a >= b and a >= c: largest = a; elif b >= c: largest = b; else: largest = c. Alternatively use the built-in max(a, b, c).
MCQ Answer Key
No.QuestionCorrect Answer
1Which keyword checks another condition when the previous if condition is False?B. elif
2What is printed by: x = 0; print("Yes" if x else "No")?C. No
3Which of these values is TRUTHY?A. "False"
4In which Python version was the match statement introduced?D. 3.10
5marks = 72. In an if-elif ladder testing >= 90, >= 75, >= 60, >= 40 in order, which block runs?C. >= 60
Chapter-6 | Loops

Read the notes, watch the video & take the MCQ test »

Answer : A loop repeats a block of code. Python provides the while loop, which repeats as long as a condition is True, and the for loop, which repeats once for each item of an iterable.

Answer : Use while when the number of repetitions is not known in advance and depends on a condition, for example reading input until the user types "quit". Use for when iterating over a known sequence or range.

Answer : An infinite loop never ends because its condition never becomes False. It is avoided by updating the loop variable inside the loop so the condition eventually fails, or by using break when a goal is reached.

Answer : range() produces integers from start up to but not including stop, increasing by step. range(5) gives 0–4, range(2, 8) gives 2–7, and range(10, 0, -2) gives 10, 8, 6, 4, 2.

Answer : 1, 4 and 7. The next value, 10, is not included because stop is exclusive.

Answer : break terminates the whole loop immediately. continue skips only the rest of the current iteration and moves on to the next iteration.

Answer : pass does nothing. It is used as a placeholder when a statement is syntactically required, such as an empty loop or function body to be completed later.

Answer : The else block runs after the loop completes normally (the condition becomes False or the items run out). It does not run if the loop is terminated by break.

Answer : The loop tries divisors and breaks when one divides the number. If no divisor is found, the loop finishes normally and else runs, reporting that the number is prime – no extra flag variable is needed.

Answer : enumerate() returns pairs of (index, item), so a loop can access both the position and the value. enumerate(items, start=1) starts counting from 1.

Answer : A nested loop is a loop inside another loop. The inner loop runs completely for each outer iteration, so the inner body runs 3 × 4 = 12 times.

Answer : total = 0; while n > 0: total += n % 10; n //= 10. n % 10 extracts the last digit and n //= 10 removes it. For 4721 the result is 14.

Answer : factorial = 1; for i in range(1, n + 1): factorial *= i. For n = 5 the result is 120.

Answer : Yes. A string is a sequence, so for ch in "Python" gives one character per iteration: P, y, t, h, o, n.

Answer : A range object does not store all its numbers in memory; it calculates each value when needed. range(1_000_000) uses the same small amount of memory as range(10).
MCQ Answer Key
No.QuestionCorrect Answer
1How many times does for i in range(2, 10, 2): execute its body?B. 4
2Which statement skips the rest of the current iteration only?A. continue
3When is the else block of a for loop SKIPPED?D. When the loop ends with break
4What is the last value produced by range(10, 0, -3)?B. 1
5What does the following print? i = 0; while i < 3: i += 1 – then print(i)C. 3
Chapter-7 | Functions

Read the notes, watch the video & take the MCQ test »

Answer : A function is a named, reusable block of code that performs a specific task when called. Advantages: code reusability, modularity (breaking a problem into parts), easier testing and debugging, and better readability.

Answer : Parameters are the variable names listed in the function definition. Arguments are the actual values passed to the function when it is called. In def add(a, b) and add(2, 3), a and b are parameters while 2 and 3 are arguments.

Answer : It returns None.

Answer : By returning several values separated by commas, which Python packs into a tuple: return low, high. The caller can unpack them: low, high = min_max(nums).

Answer : Default arguments have a value in the definition that is used when the caller omits them. In def make_bill(item, price, qty=1), calling make_bill("Pen", 10) uses qty = 1.

Answer : Keyword arguments are passed as name=value, so their order does not matter and calls become self-explanatory, e.g. make_bill(price=40, item="Ink").

Answer : *args collects any number of extra positional arguments into a tuple. **kwargs collects any number of extra keyword arguments into a dictionary. They let a function accept a variable number of arguments.

Answer : Default values are evaluated once, when the function is defined, so the same list object is shared by every call and changes accumulate between calls. Use None as the default and create a new list inside the function.

Answer : A local variable is created inside a function and exists only during that call. A global variable is defined at the top level of a module and can be read anywhere in it. Assigning to a global inside a function requires the global keyword.

Answer : It is the order in which Python looks up a name: Local scope, then Enclosing function scopes, then Global (module) scope, then Built-in names.

Answer : A lambda is a small anonymous function defined with the lambda keyword and a single expression, e.g. lambda x: x * x. It is commonly used as a short argument to functions like sorted(), map() and filter().

Answer : map(func, iterable) applies func to every item and returns an iterator of the results. filter(func, iterable) returns an iterator of only those items for which func returns a truthy value.

Answer : Recursion is when a function calls itself to solve a smaller version of the same problem. The base case is the condition under which the function returns without calling itself, which stops the recursion.

Answer : It keeps calling itself until Python’s recursion limit (about 1000 calls by default) is exceeded, and a RecursionError is raised.

Answer : A docstring is a string literal written as the first statement inside a function, describing what it does. It can be read with function_name.__doc__ or help(function_name).
MCQ Answer Key
No.QuestionCorrect Answer
1Which keyword is used to define a function in Python?B. def
2Inside def f(*args):, what is the type of args?A. tuple
3What is printed by: def f(): pass – then print(f())?D. None
4What is the output of print((lambda x, y: x * y)(3, 4))?C. 12
5Which keyword lets a function assign to a module-level variable?A. global
Chapter-8 | Lists

Read the notes, watch the video & take the MCQ test »

Answer : A list is an ordered, mutable collection of items written inside square brackets. It can store items of different types, allows duplicate values and can be nested.

Answer : Positive indexes start at 0 from the left; negative indexes start at -1 from the right. For marks = [78, 92, 65, 88, 70], marks[0] is 78 and marks[-1] is 70.

Answer : [20, 30, 40] – the items from index 1 up to, but not including, index 4.

Answer : list.reverse() reverses it in place; slicing with list[::-1] returns a new reversed list; reversed(list) returns a reverse iterator.

Answer : append(x) adds x as a single item at the end – appending [3, 4] adds one nested list. extend(iterable) adds each item of the iterable separately – extending with [3, 4] adds 3 and 4.

Answer : remove(x) deletes the first occurrence of a value. pop(i) deletes and returns the item at index i (last item by default). del list[i] deletes by index or slice without returning anything.

Answer : list.sort() sorts the list in place and returns None. sorted(iterable) returns a new sorted list and leaves the original unchanged; it also works on any iterable.

Answer : Use list.sort(reverse=True) or sorted(list, reverse=True).

Answer : key is a function applied to each item to produce the value used for comparison. sorted(words, key=len) sorts by length and key=str.lower sorts case-insensitively.

Answer : Assignment copies only the reference. Both names point to the same list object, so changing the list through one name is visible through the other. Use a.copy(), list(a) or a[:] to create a new list.

Answer : A shallow copy creates a new outer list but shares the inner (nested) objects. A deep copy, made with copy.deepcopy(), recursively copies all nested objects so changes to inner lists do not affect the copy.

Answer : A concise way to build a list: [expression for item in iterable if condition]. Example: [n * n for n in range(1, 6)] gives [1, 4, 9, 16, 25].

Answer : Divide the sum by the number of items: sum(data) / len(data). For [12, 7, 25, 3] the average is 11.75.

Answer : Python raises ValueError. Check membership first with if x in my_list: or handle the exception.

Answer : Use two indexes – the first selects the inner list (row) and the second selects the item (column). matrix[1][2] is 6.
MCQ Answer Key
No.QuestionCorrect Answer
1What is the output of print([10, 20, 30, 40][-2])?B. 30
2What does list.sort() return?C. None
3Which method removes and RETURNS the last item of a list?A. pop()
4What is the output of print([n for n in range(5) if n % 2])?D. [1, 3]
5a = [1, 2]; b = a; b.append(3). What is a?B. [1, 2, 3]
Chapter-9 | Tuples

Read the notes, watch the video & take the MCQ test »

Answer : A tuple is an ordered, immutable collection of items, usually written in parentheses, e.g. (10, 20, 30). It allows duplicates and items of different types but cannot be changed after creation.

Answer : Add a trailing comma: single = (5,). Without the comma, (5) is just the integer 5 in parentheses.

Answer : No. The commas create the tuple; t = 1, 2, 3 is a tuple. Parentheses are needed only for the empty tuple () or where the expression would otherwise be ambiguous.

Answer : Python raises TypeError: 'tuple' object does not support item assignment, because tuples are immutable.

Answer : You cannot change it in place, but you can build a new tuple from parts of the old one, e.g. days = ("Sun",) + days[1:], or convert it to a list, change the list and convert back with tuple().

Answer : Yes. The tuple itself cannot be changed to refer to different objects, but a mutable object inside it, such as a list, can still be modified, e.g. record[1].append(75).

Answer : Only two: count(x), which returns how many times x occurs, and index(x), which returns the position of the first occurrence of x.

Answer : Packing is grouping values into a tuple: student = ("Ravi", 19, "BCA"). Unpacking is assigning its items to variables: name, age, course = student.

Answer : first receives 1 and the starred name rest receives the remaining items as a list: [2, 3, 4].

Answer : Dictionary keys must be hashable. Tuples containing only immutable items are hashable; lists are mutable and therefore unhashable.

Answer : Lists use [] and are mutable; tuples use () and are immutable. Lists have many methods while tuples have only count() and index(). Tuples use less memory. Tuples (of immutable items) can be dictionary keys; lists cannot.

Answer : When the data is fixed and should not change, such as coordinates, dates, RGB colours or records returned from a function, and when you need a dictionary key.

Answer : return a, b returns the tuple (a, b), which the caller can unpack: lo, hi = stats(nums).

Answer : ('hi', 'hi', 'hi') – repetition creates a new tuple with the items repeated three times.

Answer : No. sorted() always returns a new list. Use tuple(sorted(t)) to get a sorted tuple.
MCQ Answer Key
No.QuestionCorrect Answer
1Which of the following creates a tuple with ONE element?C. (5,)
2Which of these operations is NOT allowed on a tuple?D. t.append(4)
3What is the output of print((1, 2, 2, 3).count(2))?A. 2
4After a, *b = (1, 2, 3), what is b?B. [2, 3]
5Which can be used as a dictionary key?D. (1, 2)
Chapter-10 | Dictionary

Read the notes, watch the video & take the MCQ test »

Answer : A dictionary is a mutable collection of key–value pairs written inside curly braces, e.g. {"name": "Asha", "age": 20}. Values are accessed by their keys rather than by position.

Answer : Keys must be unique and hashable (immutable types such as str, int, float or tuples of immutable items). Lists, sets and dictionaries cannot be keys. Values have no such restriction.

Answer : Since Python 3.7, dictionaries preserve insertion order as part of the language specification, so items are returned in the order they were added.

Answer : d["key"] raises KeyError if the key does not exist. d.get("key") returns None (or a supplied default, e.g. d.get("key", 0)) instead of raising an error.

Answer : Assign to the key: d["city"] = "Bhopal". If the key exists, its value is replaced; otherwise a new pair is added. update() adds or replaces several pairs at once.

Answer : pop(key) removes the given key and returns its value. popitem() removes and returns the last inserted (key, value) pair. del d[key] deletes a key without returning anything.

Answer : They return view objects that show the dictionary’s keys, values and (key, value) pairs respectively. Views reflect later changes to the dictionary and can be looped over or converted with list().

Answer : It checks whether a KEY is present: "pen" in stock. To check values use value in d.values().

Answer : freq = {}; for ch in text: freq[ch] = freq.get(ch, 0) + 1. For "banana" this gives {'b': 1, 'a': 3, 'n': 2}.

Answer : d.setdefault(key, value) returns the value of key if it exists; if it does not, it inserts key with the given value and returns that value.

Answer : A dictionary whose values are themselves dictionaries. Use chained keys: students[102]["name"] returns the name stored for student 102.

Answer : {n: n * n for n in range(1, 6)} produces {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}.

Answer : max(d, key=d.get) returns the key whose value is largest. For marks = {"Maths": 88, "Physics": 76, "English": 91} it returns "English".

Answer : Keys are unique, so the later value overwrites the earlier one: {"a": 1, "a": 2} becomes {'a': 2}.

Answer : Dictionaries are implemented as hash tables. A key’s hash is used to find its location directly, so look-ups take roughly constant time on average regardless of the dictionary’s size.
MCQ Answer Key
No.QuestionCorrect Answer
1What does {"a": 1}.get("b", 0) return?C. 0
2Which of these can NOT be a dictionary key?D. [1, 2]
3d = {"x": 1}; d["x"] = 5. What is d?A. {'x': 5}
4Looping directly over a dictionary (for k in d) gives its:B. Keys
5Which method removes a key and returns its value?D. pop()
Chapter-11 | File System and Google Drive

Read the notes, watch the video & take the MCQ test »

Answer : Variables are stored in memory and are lost when the program ends. Files store data permanently on disk so it can be reused later or shared with other programs.

Answer : Open the file with open(), read from or write to it using the file object’s methods, and close it with close() – or use a with statement, which closes it automatically.

Answer : w opens a file for writing and erases any existing content (creating the file if needed). a opens a file for appending: existing content is kept and new data is written at the end.

Answer : Both allow reading and writing. r+ requires the file to exist and keeps its content, with writing starting at the beginning and overwriting characters there. w+ creates the file if needed and erases existing content first.

Answer : x (exclusive creation) creates a new file for writing and raises FileExistsError if the file already exists, preventing accidental overwriting.

Answer : Python raises FileNotFoundError. It can be handled with try-except or avoided by checking os.path.exists() first.

Answer : read() returns the entire file (or n characters) as one string. readline() returns the next single line including its newline. readlines() returns a list containing all remaining lines.

Answer : for line in f reads one line at a time, so the whole file is never loaded into memory at once, unlike read() or readlines().

Answer : with acts as a context manager: the file is automatically closed when the block ends, even if an exception occurs, preventing resource leaks and lost data.

Answer : write(s) returns the number of characters written. It does not add a newline automatically – include "\n" yourself.

Answer : The default encoding depends on the operating system. Stating UTF-8 makes the program read and write non-English characters consistently on every computer.

Answer : tell() returns the current position in the file. seek(pos) moves the position, for example seek(0) returns to the beginning so the file can be read again.

Answer : Add b to the mode, for example open("photo.jpg", "rb") to read or "wb" to write. Data is then handled as bytes instead of strings.

Answer : Colab runs on a temporary virtual machine whose storage is deleted when the runtime ends. Mounting Google Drive with drive.mount("/content/drive") and saving under /content/drive/MyDrive keeps files permanently.

Answer : from google.colab import drive, then drive.mount('/content/drive'). After granting permission, Drive files are available under /content/drive/MyDrive.
MCQ Answer Key
No.QuestionCorrect Answer
1Which mode erases existing content before writing?D. w
2Which is the default mode of open()?A. r
3Which method returns a LIST of lines?C. readlines()
4Opening an existing file in x mode raises:B. FileExistsError
5In Colab, Google Drive files appear under which path after mounting at /content/drive?A. /content/drive/MyDrive
NumPy Chapter-1 | Array Basics

Read the notes, watch the video & take the MCQ test »

Answer : NumPy (Numerical Python) is the fundamental Python library for numerical and scientific computing. It provides the ndarray, a fast N-dimensional array of same-type values, plus mathematical functions that operate on whole arrays.

Answer : import numpy as np. The short alias np is a widely followed convention that keeps code concise and readable, e.g. np.array().

Answer : Arrays store same-type values in compact, continuous memory; they support vectorised element-wise operations executed in fast compiled code without Python loops; and they offer many built-in mathematical and statistical functions.

Answer : For a list, * repeats the list: [1, 2, 1, 2]. For an array, * multiplies each element: [2 4].

Answer : A 0-D array holds a single value and has no axes, e.g. np.array(42). Its ndim is 0 and its shape is ().

Answer : For a2 = np.array([[1,2,3,4,5,6],[11,22,33,44,55,66]]): ndim is 2 (two axes), shape is (2, 6) (2 rows, 6 columns) and size is 12 (total elements).

Answer : (2, 2, 3): two blocks, each with two rows of three elements. Its ndim is 3 and size is 12.

Answer : dtype is the data type shared by all elements. Because the list mixes ints and a float, NumPy upcasts all values to float64, giving [1. 2.5 3.].

Answer : Use astype(), e.g. np.array([1.7, 2.2]).astype(int) gives [1 2] – decimals are truncated. You can also set dtype when creating: np.array([1, 2], dtype=float).

Answer : np.arange(start, stop, step) uses a step size and excludes stop, like range(). np.linspace(start, stop, num) creates num evenly spaced values and includes stop by default.

Answer : np.zeros(shape) creates an array filled with 0 (float by default), np.ones(shape) one filled with 1, np.full(shape, value) one filled with a given value, and np.eye(n) an n × n identity matrix.

Answer : axis=0 operates down the rows, giving one result per column. axis=1 operates across the columns, giving one result per row.

Answer : sum(axis=0) gives column totals [166 162 160]; sum(axis=1) gives row totals [235 253].

Answer : itemsize is the number of bytes used by one element. An int8 array has itemsize 1 and a float64 array has itemsize 8.

Answer : pandas, SciPy, Matplotlib and scikit-learn.
MCQ Answer Key
No.QuestionCorrect Answer
1What is the shape of np.array([[1, 2, 3], [4, 5, 6]])?C. (2, 3)
2What is printed by print(np.array([1, 2]) * 3)?A. [3 6]
3What is the ndim of np.array(42)?B. 0
4Which function includes the stop value by default?D. np.linspace
5What is the dtype of np.array([1, 2.5, 3])?A. float64
NumPy Chapter-2 | Array Indexing

Read the notes, watch the video & take the MCQ test »

Answer : Array indexing is accessing an element (or a group of elements) of an array by its position. In NumPy indexes start at 0, and negative indexes count from the end.

Answer : Use the negative index -1, e.g. arr[-1]. For np.array([10, 20, 30, 40, 50]) it returns 50.

Answer : Use arr[row, column], where both indexes start from 0. For m = [[1,2,3,4],[5,6,7,8],[9,10,11,12]], m[2, 3] is 12.

Answer : Both return the same element. m[1, 2] indexes the array once with a tuple; m[1][2] first creates the row m[1] and then indexes it. The comma form is the preferred NumPy style and is more efficient.

Answer : It returns the entire row at index 1 as a 1-D array, e.g. [5 6 7 8].

Answer : Use three indexes: arr[block, row, column]. For a3 = [[[1,2,3],[11,22,33]],[[4,5,6],[44,55,66]]], a3[0, 1, 2] is 33.

Answer : Yes. Arrays are mutable: arr[0] = 99 replaces the first element. The new value is converted to the array’s dtype.

Answer : Fancy indexing passes a list or array of indexes to select several elements at once, e.g. arr[[0, 2, 4]]. The result is a new array (a copy), and indexes may repeat.

Answer : It pairs the row and column lists to select (0,2), (1,1) and (2,0), giving [3 5 7].

Answer : Using a boolean array (usually from a condition such as arr > 50) as an index. Only elements where the mask is True are returned.

Answer : A boolean array of the same shape: [False True True True False]. Using it as scores[scores >= 60] returns [82 67 91].

Answer : IndexError, for example "index 5 is out of bounds for axis 0 with size 3".

Answer : A copy. Changing the result does not change the original array. (Basic slicing, by contrast, returns a view.)

Answer : Pass a list of row indexes: m[[0, 2]].

Answer : Use m[-1, -1].
MCQ Answer Key
No.QuestionCorrect Answer
1For arr = np.array([5, 10, 15, 20]), what is arr[-2]?B. 15
2For m = np.array([[1, 2], [3, 4]]), what is m[1, 0]?A. 3
3Which indexing style returns a COPY of the data?D. arr[[0, 2]]
4What does np.array([3, 8, 1])[np.array([3, 8, 1]) > 2] return?A. [3 8]
5Accessing arr[10] on a 3-element array raises:C. IndexError
NumPy Chapter-3 | Array Slicing

Read the notes, watch the video & take the MCQ test »

Answer : Slicing extracts a portion of an array using the syntax arr[start:stop:step], where start is included, stop is excluded and step is the gap between elements.

Answer : start defaults to 0, stop defaults to the end of the array (for a positive step), and step defaults to 1.

Answer : [20 30 40 50] – the elements at indexes 1, 2, 3 and 4.

Answer : Use a step of 2: arr[::2].

Answer : Use a step of -1: arr[::-1].

Answer : Use a negative start index: arr[-3:].

Answer : The slice starts at index 5 (60) and moves backwards in steps of 2, stopping before index 1: it selects indexes 5 and 3, giving [60 40].

Answer : Provide a slice for each axis separated by a comma: arr[row_slice, column_slice]. For example m[0:2, 1:3] selects rows 0–1 and columns 1–2.

Answer : Use m[:, 0] – the colon selects all rows and 0 selects the first column.

Answer : List slicing returns a new list (a copy). NumPy slicing returns a view that shares memory with the original array, so modifying the slice also modifies the original.

Answer : Call .copy() on the slice: part = arr[1:4].copy(). The copy has its own data.

Answer : It assigns 0 to every element in the slice (indexes 0 and 1), changing the original array. A single value is broadcast to all selected positions.

Answer : Views avoid copying data, which saves memory and time, especially for large arrays. The trade-off is that changes through the view affect the original.

Answer : Every second row (rows 0 and 2) and every third column (columns 0 and 3), producing a 2 × 2 array.

Answer : m[1, :] uses an integer for the row, so the result is 1-D with shape (4,). m[1:2, :] uses a slice, so the row dimension is kept and the shape is (1, 4).
MCQ Answer Key
No.QuestionCorrect Answer
1What is np.array([1, 2, 3, 4, 5])[1:4]?C. [2 3 4]
2Which slice reverses an array?A. arr[::-1]
3For a 2-D array m, which expression gives the LAST column?D. m[:, -1]
4b = a[0:2]; b[0] = 50. What happens to a?B. a[0] becomes 50
5What is the shape of m[1:2, :] for a 3 × 4 array?C. (1, 4)
NumPy Chapter-4 | Array Copy vs View

Read the notes, watch the video & take the MCQ test »

Answer : A copy is a new array with its own data, so changes to it do not affect the original. A view is a new array object that shares the original’s data, so changes made through either one are visible in both.

Answer : arr.copy() creates a copy; arr.view() creates a view. Basic slicing such as arr[1:4] also creates a view.

Answer : base is None if the array owns its data (for example a copy). For a view, base refers to the array that owns the data.

Answer : Use np.shares_memory(a, b), which returns True if the arrays use any of the same memory. Checking b.base is a also identifies a direct view.

Answer : Neither. Assignment creates no new array; a and b are two names for the same object, so b is a is True.

Answer : Fancy (integer-array) indexing, such as arr[[1, 2, 3]], and boolean indexing, such as arr[arr > 5], always return copies.

Answer : Basic slicing, arr.view(), the transpose arr.T, and usually reshape() and ravel() (when the data layout allows it).

Answer : Views avoid copying data, saving memory and time. This is important when working with very large arrays.

Answer : Modifying a view unintentionally changes the original array, which can corrupt data that other parts of the program rely on.

Answer : [60 77 38 90]. t is a view of the first two elements, so adding 5 to t also changes marks.

Answer : Take a copy of the slice: t = marks[:2].copy(). Then t += 5 leaves marks unchanged.

Answer : flatten() always returns a new copy. ravel() returns a view whenever possible (and a copy only if needed), so it is faster but changes may affect the original.

Answer : arr[0] changes as well, because the view and the original share the same data.

Answer : When you need to modify extracted data without affecting the source, when storing a snapshot of an array’s current values, or when passing data to code that might modify it.

Answer : No. Boolean indexing selects an arbitrary set of elements that cannot be described by a simple stride pattern, so NumPy returns a copy.
MCQ Answer Key
No.QuestionCorrect Answer
1Which method creates an array that does NOT share data with the original?B. copy()
2For c = arr.copy(), what is c.base?A. None
3Which of these returns a COPY?D. arr[[0, 1]]
4Which function checks whether two arrays use the same memory?C. np.shares_memory
5v = arr.view(); arr[0] = 7. What is v[0]?D. 7
NumPy Chapter-5 | Array Shape and Reshape

Read the notes, watch the video & take the MCQ test »

Answer : shape is a tuple giving the number of elements along each dimension (axis). For a 2-D array it is (rows, columns); for example a 2 × 3 matrix has shape (2, 3).

Answer : (4,) – a tuple with one value. The trailing comma shows it is a one-element tuple.

Answer : ndmin specifies the minimum number of dimensions. np.array([1, 2, 3, 4], ndmin=3) produces shape (1, 1, 4).

Answer : Reshaping changes the shape (number of dimensions or elements per dimension) of an array without changing its data, using reshape().

Answer : The total number of elements must remain the same. An array of 12 elements can be reshaped to (3, 4), (2, 6) or (2, 3, 2), but not to (5, 3).

Answer : NumPy raises ValueError, e.g. "cannot reshape array of size 12 into shape (5,3)".

Answer : -1 stands for an unknown dimension that NumPy calculates automatically from the array size. Only one dimension can be -1. arr.reshape(4, -1) for 12 elements gives shape (4, 3).

Answer : Use arr.reshape(-1), arr.ravel() or arr.flatten().

Answer : ravel() returns a flattened view of the original data whenever possible, so it is fast but changes may affect the original. flatten() always returns a new copy, so changes never affect the original.

Answer : reshape() returns a view whenever the memory layout allows it; otherwise it returns a copy. Modifying a reshaped view changes the original array.

Answer : The transpose swaps rows and columns, so element (i, j) moves to (j, i). Use arr.T or np.transpose(arr); a (2, 3) array becomes (3, 2).

Answer : arr.reshape(-1, 1), giving shape (12, 1) – 12 rows and 1 column.

Answer : np.arange(1, 13).reshape(3, 4) gives [[1 2 3 4] [5 6 7 8] [9 10 11 12]].

Answer : shape is (2, 3, 4) and size is 2 × 3 × 4 = 24.

Answer : Many algorithms and libraries expect data in a specific shape, for example a 2-D (samples × features) matrix or a column vector, and images are often reshaped between 2-D and 1-D forms. reshape() converts data without copying where possible.
MCQ Answer Key
No.QuestionCorrect Answer
1An array has 12 elements. Which reshape is INVALID?C. (5, 2)
2np.arange(8).reshape(2, -1).shape is:A. (2, 4)
3Which method ALWAYS returns a copy when flattening?C. flatten()
4What is the shape of the transpose of an array with shape (2, 5)?D. (5, 2)
5How many dimensions can be given as -1 in one reshape() call?A. Only one
NumPy Chapter-6 | Array Iterating

Read the notes, watch the video & take the MCQ test »

Answer : Iterating means visiting the elements of an array one by one, usually with a for loop, to read or process them.

Answer : The loop moves along the first axis, so each iteration gives one row as a 1-D array.

Answer : Three: one for the blocks, one for the rows within each block and one for the elements within each row.

Answer : np.nditer() is an efficient iterator that visits every element of an array of any dimension using a single loop, avoiding nested loops.

Answer : Pass a slice to nditer: for x in np.nditer(arr[:, ::2]): …

Answer : Use the op_dtypes argument together with flags=["buffered"], for example np.nditer(arr, flags=["buffered"], op_dtypes=["float64"]). Buffering provides temporary space for the converted values.

Answer : Open the iterator with op_flags=["readwrite"] inside a with block and assign through x[...] = new_value.

Answer : It yields pairs of (index tuple, value) for every element, e.g. ((0, 1), 20), so you know the position of each element.

Answer : The loop variable is a separate value; reassigning it only changes the local name. To modify the array you must assign through an index (arr[i] = …) or use nditer with readwrite and x[...].

Answer : Vectorisation means performing an operation on whole arrays at once (e.g. arr * 2) instead of looping over elements in Python. NumPy runs these operations in optimised compiled code.

Answer : They are much faster on large arrays, use shorter and more readable code, and reduce chances of indexing mistakes.

Answer : (arr ** 2).sum(). For [3, 8, 1, 9, 4] the result is 171.

Answer : For a normally created array it visits elements row by row (C order): all elements of the first row, then the second row, and so on.

Answer : For small arrays, for logic that cannot be expressed with vectorised operations, or when processing items with side effects such as printing or writing files.

Answer : 1 2 3 4
MCQ Answer Key
No.QuestionCorrect Answer
1Looping with for row in arr over a 2-D array gives each:D. Row
2Which function iterates over every element of an N-D array with ONE loop?A. np.nditer
3Which function yields (index, value) pairs?C. np.ndenumerate
4Which op_flags value allows nditer to modify elements?B. "readwrite"
5Why is (arr ** 2).sum() preferred over a Python loop for large arrays?B. It is vectorised and much faster
NumPy Chapter-7 | Array Join

Read the notes, watch the video & take the MCQ test »

Answer : Joining means combining the contents of two or more arrays into a single array, either along an existing axis (concatenation) or along a new axis (stacking).

Answer : Concatenation (np.concatenate) joins arrays along an existing axis, so the number of dimensions is unchanged. Stacking (np.stack) joins arrays along a new axis, so the result has one more dimension.

Answer : np.concatenate((arr1, arr2, ...), axis=0). The arrays are passed as a tuple or list, and axis selects the joining direction (0 by default).

Answer : Along axis 0 the rows are added, giving a 4 × 2 array. Along axis 1 the columns are added, giving a 2 × 4 array.

Answer : All arrays must have the same number of dimensions and the same size in every dimension except the axis along which they are joined; otherwise ValueError is raised.

Answer : A new 2-D array [[1 2 3] [4 5 6]] with shape (2, 3), because the arrays are stacked along a new first axis.

Answer : [[1 4] [2 5] [3 6]] with shape (3, 2) – corresponding elements are paired along the new second axis.

Answer : All input arrays must have exactly the same shape.

Answer : For 1-D arrays it joins them end to end into one longer 1-D array. For 2-D arrays it places them side by side, adding columns (equivalent to concatenation along axis 1).

Answer : It stacks arrays vertically, one below the other, adding rows. Two 1-D arrays of length 3 become a 2 × 3 array.

Answer : dstack joins arrays along the third axis (depth). Two 1-D arrays of length 3 produce shape (1, 3, 2).

Answer : Compute row sums with marks.sum(axis=1), reshape them into a column with reshape(-1, 1), then join with np.hstack((marks, totals)).

Answer : np.vstack() or np.stack(..., axis=0); both place each array as a separate row.

Answer : No. It returns a new array containing copies of the data; the original arrays are unchanged.

Answer : Along axis 0 the column counts must match, but one has 2 columns and the other has 3, so NumPy raises ValueError.
MCQ Answer Key
No.QuestionCorrect Answer
1Which function joins arrays along a NEW axis?B. np.stack
2Concatenating two (2, 3) arrays with axis=1 gives shape:C. (2, 6)
3np.vstack((np.array([1, 2]), np.array([3, 4]))) returns:A. [[1 2] [3 4]]
4np.hstack on two 1-D arrays of length 3 gives an array of shape:D. (6,)
5Which function joins along the third axis (depth)?C. np.dstack
NumPy Chapter-8 | Array Split

Read the notes, watch the video & take the MCQ test »

Answer : Splitting is the reverse of joining: it breaks one array into several smaller arrays. NumPy returns the pieces as a list of arrays.

Answer : np.split(arr, n) requires the array to divide into n equal parts and raises ValueError otherwise. np.array_split(arr, n) also works when equal division is impossible, making the first parts one element larger.

Answer : Into parts of sizes 3, 2 and 2: [1 2 3], [4 5] and [6 7].

Answer : ValueError: array split does not result in an equal division.

Answer : A Python list whose items are NumPy arrays.

Answer : Pass a list of indexes instead of a number: np.split(arr, [3, 7]) gives arr[:3], arr[3:7] and arr[7:].

Answer : Three arrays: [10 11 12], [13 14 15 16] and [17 18 19].

Answer : Use axis=0 (the default), e.g. np.array_split(m, 2), or the shortcut np.vsplit(m, 2).

Answer : Use axis=1, e.g. np.array_split(m, 3, axis=1), or the shortcut np.hsplit(m, 3).

Answer : hsplit splits along columns (axis 1), vsplit along rows (axis 0) and dsplit along the third axis (depth, axis 2). They are the opposites of hstack, vstack and dstack.

Answer : The first two columns: [[1 2] [5 6] [9 10]].

Answer : Index the returned list, e.g. parts = np.array_split(arr, 3); parts[1]. You can also unpack: a, b, c = np.array_split(arr, 3).

Answer : It is used to divide data into training and testing sets, to process large data in batches, and to separate features (columns) from labels.

Answer : Yes, when given a number of sections it requires equal division like np.split(). Use np.array_split(..., axis=1) for uneven column splits.

Answer : Yes. np.vstack(np.vsplit(m, 3)) rebuilds the original array m, because vsplit separates rows that vstack joins back together.
MCQ Answer Key
No.QuestionCorrect Answer
1Which function can split 7 elements into 3 parts WITHOUT error?C. np.array_split
2np.split(np.arange(6), [2, 4]) returns how many arrays?A. 3
3np.array_split returns a:D. List of arrays
4To split a 2-D array into column groups you use:B. np.hsplit
5np.array_split(np.arange(1, 8), 3)[0] is:C. [1 2 3]
NumPy Chapter-9 | Array Search

Read the notes, watch the video & take the MCQ test »

Answer : It returns a tuple of arrays containing the indexes of the elements where the condition is True – one array per dimension. For a 1-D array, np.where(cond)[0] gives the index array.

Answer : [0 2 5] – the positions at which the value 4 occurs.

Answer : np.where returns one index array per dimension so that the same function works for arrays of any dimension. A 1-D array has one dimension, so the tuple contains a single array.

Answer : A tuple containing an empty array, e.g. (array([], dtype=int64),); np.where(...)[0] prints [].

Answer : It performs a binary search on a sorted array and returns the index at which a value should be inserted so that the array remains sorted.

Answer : If the value already exists, side="left" (the default) returns the index of its first occurrence, while side="right" returns the index just after its last occurrence. For [10,20,30,40,50] and 30 they return 2 and 3.

Answer : The array must be sorted in ascending order; otherwise the result is not meaningful.

Answer : Yes. Pass a list or array of values, e.g. np.searchsorted(arr, [5, 25, 60]) returns [0 2 5].

Answer : They return the index of the maximum and minimum value respectively. If the extreme value occurs more than once, the index of the first occurrence is returned.

Answer : m.argmax() gives a flat index; convert it with np.unravel_index(m.argmax(), m.shape) to get (row, column).

Answer : Two arrays: the row indexes and the column indexes of the matching elements. For m = [[5,8,2],[9,8,1]] it returns ([0 1], [1 1]).

Answer : np.where returns separate index arrays per dimension; np.argwhere returns a 2-D array where each row is the full index (e.g. [row, column]) of one match.

Answer : The indexes of the non-zero (truthy) elements, as a tuple of arrays like np.where. For [0, 3, 0, 5] it returns positions [1 3].

Answer : Use the in operator (9 in arr), np.isin(values, arr) for several values, or np.any(arr == value).

Answer : Use np.count_nonzero(arr > 5) or (arr > 5).sum(), because True counts as 1.
MCQ Answer Key
No.QuestionCorrect Answer
1np.where(np.array([1, 5, 1]) == 1)[0] returns:A. [0 2]
2Which function performs a binary search on a sorted array?D. np.searchsorted
3np.searchsorted([10, 20, 30], 25) returns:B. 2
4For np.array([3, 9, 9, 1]).argmax(), the result is:C. 1
5Which function converts a flat index into (row, column)?A. np.unravel_index
NumPy Chapter-10 | Array Sort

Read the notes, watch the video & take the MCQ test »

Answer : Sorting is arranging elements in an ordered sequence – numerically or alphabetically, in ascending or descending order.

Answer : No. np.sort(arr) returns a new sorted copy and leaves the original unchanged.

Answer : np.sort(arr) returns a sorted copy and keeps the original. arr.sort() sorts the array in place, changing it, and returns None.

Answer : Alphabetically (lexicographically, by character code). For ["mango", "apple", "kiwi", "banana"] the result is ['apple' 'banana' 'kiwi' 'mango'].

Answer : False is treated as 0 and True as 1, so all False values come before True values.

Answer : NumPy sorts only in ascending order, so reverse the result: np.sort(arr)[::-1]. For numbers, -np.sort(-arr) also works.

Answer : Along the last axis (axis=-1), so each row is sorted independently.

Answer : Use axis=0: np.sort(m, axis=0).

Answer : It flattens the array and returns all values sorted in a single 1-D array.

Answer : It returns the indexes that would sort the array. For marks [82, 67, 91, 74] it returns [1 3 0 2].

Answer : Compute order = marks.argsort() and index the names with it: names[order]. Use order[::-1] for highest marks first.

Answer : students[marks.argsort()[::-1][:2]] – reverse the ascending order to descending and take the first two.

Answer : [[2 7 9] [1 4 8]] – each row is sorted separately.

Answer : Yes, with the kind argument, e.g. np.sort(arr, kind="stable") or kind="mergesort". "stable" keeps equal elements in their original order. The default is "quicksort" (implemented as an introsort).

Answer : To rank values (e.g. top scorers), find medians and percentiles, prepare data for binary search (searchsorted) and present results in a meaningful order.
MCQ Answer Key
No.QuestionCorrect Answer
1What does arr.sort() return?C. None
2np.sort(np.array([True, False, True])) gives:A. [False True True]
3Which expression sorts an array in descending order?B. np.sort(arr)[::-1]
4np.array([30, 10, 20]).argsort() returns:D. [1 2 0]
5To sort every COLUMN of a 2-D array you use:A. axis=0
NumPy Chapter-11 | Array Filter

Read the notes, watch the video & take the MCQ test »

Answer : Filtering is creating a new array from only those elements of an existing array that meet a condition.

Answer : A list or array of True/False values with the same length as the array. When used as an index, elements at True positions are kept and those at False positions are dropped.

Answer : [41 43] – only the elements at the True positions are selected.

Answer : Apply a comparison to the array, e.g. mask = arr > 20, which returns a boolean array. Then use it as an index: arr[mask] or simply arr[arr > 20].

Answer : arr[arr % 2 == 0].

Answer : & for AND, | for OR and ~ for NOT. Each condition must be enclosed in parentheses, e.g. arr[(arr >= 60) & (arr < 90)].

Answer : and and or need a single True/False value, but an array of many booleans has no single truth value, so Python raises ValueError ("The truth value of an array with more than one element is ambiguous").

Answer : & and | have higher precedence than comparison operators. Without parentheses, arr > 50 & arr < 80 would be evaluated as arr > (50 & arr) < 80, which is wrong or raises an error.

Answer : The result is a 1-D array of the selected elements, because the kept elements no longer form a rectangle.

Answer : data[data[:, 1] >= 60]. The 1-D mask on the column selects whole rows.

Answer : It returns a new array taking elements from x where the condition is True and from y where it is False, e.g. np.where(temps == -999, 0, temps) replaces -999 with 0.

Answer : Assign to the masked positions: arr[arr == -999] = 30 changes those elements directly in the original array.

Answer : np.count_nonzero(condition) or condition.sum(), e.g. np.count_nonzero(temps == -999).

Answer : A copy. Changing the filtered result does not change the original array (assignment through arr[mask] = value does change it, because it modifies the original directly).

Answer : Filter first, then average: temps[temps != -999].mean().
MCQ Answer Key
No.QuestionCorrect Answer
1Which operator means AND when combining NumPy conditions?C. &
2np.array([5, 15, 25])[np.array([5, 15, 25]) > 10] returns:A. [15 25]
3What does ~ do in a NumPy condition?D. Inverts (NOT) the condition
4Filtering a 2-D array with m[m > 10] returns an array with how many dimensions?B. 1
5Which call replaces negative values with 0 and keeps others?A. np.where(arr < 0, 0, arr)
Pandas Chapter-1 | Pandas Basics

Read the notes, watch the video & take the MCQ test »

Answer : pandas is an open-source Python library for data manipulation and analysis. It provides fast, flexible data structures – Series and DataFrame – for working with labelled, tabular data.

Answer : pandas was created by Wes McKinney, who began developing it in 2008. The name is derived from “panel data”, an econometrics term for multi-dimensional structured data sets.

Answer : Install it with pip install pandas (it is already available in Google Colab) and import it with import pandas as pd.

Answer : Print pd.__version__ after importing pandas.

Answer : Series, a one-dimensional labelled array, and DataFrame, a two-dimensional labelled table of rows and columns.

Answer : A Series is a one-dimensional labelled array that can hold data of any type. Each value is associated with an index label, like one column of a spreadsheet.

Answer : A DataFrame is a two-dimensional labelled data structure with rows and columns, similar to a spreadsheet or SQL table. Each column is a Series and columns can have different data types.

Answer : A DataFrame is a collection of Series that share the same row index; selecting one column of a DataFrame returns a Series.

Answer : Reading and writing files (CSV, Excel, JSON, SQL), cleaning data (missing values, duplicates, types), selecting/filtering/sorting data, and grouping and computing statistics.

Answer : pandas is built on NumPy; its columns are stored using NumPy arrays (or similar array types), which gives it fast numerical performance.

Answer : A NumPy array holds a single data type and is indexed by position, while a pandas DataFrame can hold a different data type in each column and has row labels and column names. NumPy is aimed at numerical computing; pandas is aimed at tabular data analysis.

Answer : A tuple (number of rows, number of columns). For a DataFrame of 3 students and 3 columns it returns (3, 3).

Answer : Load the data (read_csv), explore it (head, info, describe), clean it (missing values, duplicates, types), analyse it (filter, sort, group, statistics) and save the results (to_csv).

Answer : A RangeIndex of integers starting from 0 (0, 1, 2, …), unless an index is specified.

Answer : Use its label: marks["Meera"] returns 91 for marks = pd.Series([82, 67, 91], index=["Asha", "Ravi", "Meera"]).
MCQ Answer Key
No.QuestionCorrect Answer
1Which is the conventional way to import pandas?A. import pandas as pd
2A two-dimensional labelled table in pandas is called a:C. DataFrame
3pandas is built on top of which library?B. NumPy
4What does df.shape return for a table with 5 rows and 3 columns?D. (5, 3)
5Selecting a single column of a DataFrame returns a:A. Series
Pandas Chapter-2 | Pandas Series

Read the notes, watch the video & take the MCQ test »

Answer : A Series is a one-dimensional labelled array that holds data of any type. It consists of values and an index of labels for those values.

Answer : A RangeIndex 0, 1, 2, … up to n − 1, where n is the number of values.

Answer : Pass the index argument: pd.Series([31.5, 29.0, 33.2], index=["Mon", "Tue", "Wed"]).

Answer : The dictionary keys become the index labels and the values become the Series values. If an index list is also given, only those keys are used, in that order.

Answer : A Series with the scalar value 5 repeated for each label: a 5, b 5, c 5.

Answer : name gives the Series a title. It is displayed when the Series is printed and becomes the column name if the Series is added to a DataFrame.

Answer : loc selects by index label and includes the end label in slices. iloc selects by integer position and excludes the end position in slices, like Python lists.

Answer : The values for Ravi, Meera and John – the end label is included in label-based slicing.

Answer : s.iloc[0] for the first value and s.iloc[-1] for the last.

Answer : Use a boolean condition as an index: marks[marks >= 75] returns only the values that satisfy the condition, with their labels.

Answer : When two Series are combined, pandas matches values by index label, not by position. Labels present in only one Series produce NaN in the result.

Answer : NaN (Not a Number) marks a missing value. Methods such as mean(), sum() and count() skip NaN values by default.

Answer : isna() detects missing values, fillna(value) replaces them, and dropna() removes them.

Answer : A Series that counts how many times each distinct value occurs, sorted by count in descending order by default.

Answer : count() returns the number of non-missing values, while size returns the total number of values including NaN.
MCQ Answer Key
No.QuestionCorrect Answer
1pd.Series([5, 6, 7]).iloc[1] returns:B. 6
2Which accessor uses LABELS and includes the slice end?D. loc
3When a Series is created from a dictionary, the keys become the:A. Index labels
4pd.Series([1, None, 3]).count() returns:C. 2
5Adding two Series with partly different labels gives NaN for:B. Labels present in only one Series
Pandas Chapter-3 | Pandas DataFrame

Read the notes, watch the video & take the MCQ test »

Answer : A DataFrame is a two-dimensional, labelled data structure in pandas, made of rows and columns like a spreadsheet or SQL table. Each column is a Series and columns may have different data types.

Answer : Pass a dictionary of lists to pd.DataFrame(): the keys become column names and the lists become column values, e.g. pd.DataFrame({"Name": ["Asha", "Ravi"], "Age": [20, 21]}). All lists must have the same length.

Answer : Pass a list of lists and the column names: pd.DataFrame(rows, columns=["Item", "Price", "Qty"]).

Answer : df["Marks"] (a single name) returns a Series. df[["Marks"]] (a list of names) returns a DataFrame with one column.

Answer : shape returns (rows, columns). columns returns the column labels, which can be converted to a list with df.columns.tolist().

Answer : loc selects rows and columns by labels and includes the end label in slices. iloc selects by integer positions and excludes the end position in slices.

Answer : df.loc[2, "Name"]. Using positions, df.iloc[2, 0] would give the same cell if Name is the first column.

Answer : set_index("Name") returns a new DataFrame in which the Name column is used as the row index (labels), allowing access such as df.loc["John", "Marks"].

Answer : Index the DataFrame with a boolean condition on a column: df[df["Marks"] >= 75]. Combine conditions with & and |, each condition in parentheses.

Answer : It checks whether each value is in a given list, e.g. df[df["Course"].isin(["MCA", "BBA"])] keeps rows whose course is MCA or BBA.

Answer : Assign to a new column name: df["Percent"] = df["Marks"] / 500 * 100. The values are calculated for every row at once.

Answer : df.drop(columns=["Percent"]) removes a column and df.drop(index=0) removes the row with label 0. Both return a new DataFrame, so assign the result.

Answer : These methods return a new DataFrame and do not modify the original. You must assign the result, e.g. df = df.drop(columns=["x"]).

Answer : df.sort_values("Marks", ascending=False).

Answer : It splits the rows into groups by course, takes the Marks column in each group and returns the average marks for every course.
MCQ Answer Key
No.QuestionCorrect Answer
1df[["Name", "Age"]] returns a:C. DataFrame
2df.iloc[0, 1] selects:A. First row, second column
3Which expression filters students with Marks above 80?D. df[df["Marks"] > 80]
4df.loc[1:3] on a default integer index returns how many rows?B. 3
5Which method removes a column?A. df.drop(columns=[...])
Pandas Chapter-4 | CSV Files and DataFrames

Read the notes, watch the video & take the MCQ test »

Answer : A CSV (Comma-Separated Values) file is a plain-text file that stores a table: each line is a row and the values in a row are separated by commas. The first line usually holds the column names.

Answer : Use pd.read_csv("file.csv"), which returns a DataFrame. The first row is used as the header by default.

Answer : Pass the separator: pd.read_csv("file.csv", sep=";") or sep="\t" for tab-separated files.

Answer : Use the index_col option, e.g. pd.read_csv("students.csv", index_col="Roll").

Answer : Use usecols=["Name", "Marks"] to select columns and nrows=100 to read only the first 100 rows.

Answer : Use header=None and provide column names with names=[...], e.g. pd.read_csv("data.csv", header=None, names=["Roll", "Name"]).

Answer : head(n) returns the first n rows and tail(n) the last n rows of a DataFrame; n is 5 by default. They are used for a quick look at the data.

Answer : info() prints the number of rows, each column’s name, non-null count and data type, and the memory usage of the DataFrame.

Answer : For numeric columns it shows count, mean, standard deviation, minimum, 25th/50th/75th percentiles and maximum.

Answer : As NaN (Not a Number), the marker for a missing value. A numeric column containing NaN is stored as float.

Answer : df.isna().sum() returns the number of missing values per column.

Answer : dropna() removes rows (or columns) containing missing values. fillna(value) replaces missing values with a given value, such as 0 or the column mean.

Answer : df.fillna({"Marks": df["Marks"].mean()}) or df["Marks"] = df["Marks"].fillna(df["Marks"].mean()).

Answer : df.to_csv("output.csv", index=False). Without index=False the row index is written as an extra unnamed first column.

Answer : Mount Drive with from google.colab import drive; drive.mount('/content/drive'), then read it with pd.read_csv("/content/drive/MyDrive/students.csv").
MCQ Answer Key
No.QuestionCorrect Answer
1Which function reads a CSV file into a DataFrame?C. pd.read_csv()
2How many rows does df.head() show by default?A. 5
3Which option prevents the index from being written by to_csv()?B. index=False
4An empty cell in a numeric CSV column is read as:D. NaN
5Which method gives count, mean, std, min, quartiles and max?C. describe()