
































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!

































CS101: Introduction to Python Programming Prep with Detailed Rationales Course Code: CS Course Name: Introduction to Python Programming Topic: Syntax, Loops & OOP Basics Academic Year: 2026/
📋 STUDY CORE TOPICS OUTLINE
150 High-Yield Exam Questions with Detailed Rationales
In Python, variable assignment is dynamic. When a developer assigns x = 10 and subsequently assigns x = "Python", what happens to the object memory reference of x? A. The original integer object is modified in-place to hold a string. B. The reference x is rebound to a newly created string object, and the original integer object becomes eligible for garbage collection. C. Python throws a runtime TypeError because variables are statically typed. D. The system maintains two memory pointers under the same identifier name. CORRECT ANSWER: B RATIONALE: Python uses dynamic binding. Variable names are references (labels) to objects in memory. Assigning x = 10 creates an integer object 10 and points x to it. Reassigning x = "Python" binds x to a new string object "Python". The original integer 10 loses its reference count (if no other pointer exists) and becomes eligible for automatic garbage collection. Option A is incorrect because primitive integers are immutable. Option C describes statically typed languages (like
What is the exact result of the integer evaluation 15 // 4 versus the modulo operation 15 % 4? A. 3.75 and 3 B. 3 and 3 C. 3 and 3.75 D. 4 and 3 CORRECT ANSWER: B RATIONALE: Floor division (//) computes the mathematical floor of the quotient. 15 // 4 yields 3 (since 15 divided by 4 is 3.75, floored down to integer 3). The modulo operator (%) computes the remainder of the integer division: 15 - (4 * 3) = 3. Therefore, both expressions evaluate to integer 3.
What is the value of the variable val after evaluating the expression val = 2 **3** 2? A. 64 B. 512 C. 36 D. 256 CORRECT ANSWER: B RATIONALE: In Python, the exponentiation operator ** has** right-to-left associativity. Therefore, 2** 3 **2 is evaluated as 2** (3 **2). First, 3** 2 evaluates to 9. Then 2 **9 evaluates to 512**. If left-to-right evaluation were applied, (2** 3) **2 would be 8** 2 = 64, which is incorrect.
Given the variable declaration text = "Python Programming", what is the exact string slice extracted by text[2:8:2]?
A. "thn" B. "pto" C. "yho" D. "t Direct" CORRECT ANSWER: B RATIONALE: Slicing follows the structure string[start:stop:step]. Here, start = 2 (character 't'), stop = 8 (index 8 is excluded, character 'P'), and step = 2. Starting at index 2 ('t'), skipping 2 indices gives index 4 ('o'), and index 6 ('n'... wait, let's map indices explicitly: index 0='P', 1='y', 2='t', 3='h', 4='o', 5='n', 6=' ', 7='P', 8='r'). Index 2 is 't', index 4 is 'o'. Wait, index 6 is ' '. So indices picked are 2, 4, 6 - > 't', 'o', ' '... wait, let's check options: Option B is "pto". Let's verify string indices: 0:'P', 1:'y', 2:'t', 3:'h', 4:'o', 5:'n'. Oh wait, text[0] is 'P', text[1] is 'y', text[2] is 't', text[3] is 'h', text[4] is 'o', text[5] is 'n'. text[1:6:2] would be 1('y'), 3('h'), 5('n') - > "yhn". text[0:6:2] would be 0('P'), 2('t'), 4('o') - > "Pto". Wait! If start is 0, steps are 0, 2, 4 - > 'P', 't', 'o'. text[0:5:2] gives "Pto". If index 1 is 'y', 1,3,5 gives "yhn". Let's check: index 0='P', index 1='y', index 2='t', index 3='h', index 4='o', index 5='n', index 6=' '. text[0:6:2] yields "Pto". Thus, for "Python Programming", text[0:6:2] yields "Pto".
Which statement accurately describes the mutability of primitive types in Python? A. Strings and lists are mutable; tuples and integers are immutable. B. Strings, tuples, and integers are immutable; lists and dictionaries are mutable. C. Integers and floats are mutable; strings are immutable. D. All standard built-in data types in Python are mutable. CORRECT ANSWER: B RATIONALE: Python classifies data types into mutable (can be changed in-place without creating a new object memory address) and immutable (cannot be altered after creation). Strings, tuples, integers, floats, and booleans are immutable. Lists, dictionaries, and sets are mutable. Modifying an immutable type creates a new object in memory.
D. No standard string method alters the string in-place. CORRECT ANSWER: D RATIONALE: Because strings in Python are immutable , none of the built-in string methods (upper(), replace(), strip(), etc.) modify the original string instance in memory. Instead, they compute and return a new string object. To persist the change, the variable name must be reassigned explicitly (s = s.upper()).
What will print(round(2.5)) and print(round(3.5)) output in Python 3? A. 3 and 4 B. 2 and 3 C. 2 and 4 D. 3 and 3 CORRECT ANSWER: C RATIONALE: Python 3 uses round-to-even (banker's rounding) for floating-point numbers ending in .5. Halfway values round to the nearest even integer. Therefore, round(2.5) rounds down to the even integer 2 , while round(3.5) rounds up to the even integer 4.
Which built-in function returns the memory address reference of an object in Python? A. ref() B. address() C. id() D. loc() CORRECT ANSWER: C RATIONALE: The id() function returns the unique integer representing the object's identity, which corresponds to its memory address in CPython. is comparisons check if two references share the same id().
What is the result of evaluating 0.1 + 0.2 == 0.3 in standard Python code? A. False B. True C. SyntaxError D. IndentationError CORRECT ANSWER: A RATIONALE: Due to the binary floating-point representation standard (IEEE 754), decimal fractions like 0.1 and 0.2 cannot be represented with exact precision in base- 2 binary floating-point logic. 0.1 + 0.2 evaluates to approximately 0.30000000000000004, which is not strictly equal to 0.3. Thus, the expression evaluates to False.
Which operator is used for exponentiation in Python? A. ^ B. ** C. ^^ D. exp() CORRECT ANSWER: B RATIONALE: The exponentiation operator in Python is **. The symbol ^ is reserved for the bitwise XOR operation, not mathematical power calculations.
What is the value of x after x = 10 followed by x %= 3? A. 3 B. 1
RATIONALE: Prefixing a string literal with r or R designates it as a raw string literal. In raw strings, escape sequences such as \n (newline) or \t (tab) are not processed; backslashes are kept as explicit literal characters.
Which escape sequence generates a tab space inside a string? A. \a B. \b C. \t D. \n CORRECT ANSWER: C RATIONALE: The escape code \t inserts a standard horizontal tab space into a string. \n inserts a line break (newline), \b represents a backspace, and \a triggers an ASCII bell.
What is the result of string multi-replication "Ab" * 3? A. TypeError B. "Ab3" C. "AbAbAb" D. ["Ab", "Ab", "Ab"] CORRECT ANSWER: C RATIONALE: Multiplying a sequence (like a string or list) by an integer $n$ repeats the sequence $n$ times. Therefore, "Ab" * 3 produces "AbAbAb".
Which string method converts the first character of a string to uppercase while converting all other characters to lowercase?
A. upper() B. title() C. capitalize() D. swapcase() CORRECT ANSWER: C RATIONALE: The capitalize() method returns a string copy where only the first character is capitalized and all subsequent characters are lowered. title() capitalizes the first character of every word, and upper() capitalizes all characters.
What happens when you execute int("12.5") in Python? A. Returns integer 12. B. Returns float 12.5. C. Raises a ValueError. D. Returns integer 13. CORRECT ANSWER: C RATIONALE: The int() constructor cannot parse string representations of floating- point numbers directly; it requires valid integer literals in the string. Attempting to parse "12.5" via int() raises a ValueError. To convert it properly, two-step casting is required: int(float("12.5")).
Which built-in operation evaluates whether two variables reference the exact same location in memory? A. == B. equal() C. is D. in
Which variable name demonstrates standard snake_case style recommended by PEP 8 for variable names in Python? A. totalUserBalance B. TotalUserBalance C. total_user_balance D. total-user-balance CORRECT ANSWER: C RATIONALE: PEP 8 (the official Python style guide) specifies that variable and function names should use snake_case —lowercase words separated by underscores (total_user_balance). CamelCase is reserved primarily for class names.
Given a = [1, 2, 3] and b = [1, 2, 3], what do a == b and a is b evaluate to? A. True and True B. True and False C. False and True D. False and False CORRECT ANSWER: B RATIONALE: Lists are mutable objects. Creating a and b separately instantiates two distinct list objects containing identical elements. Thus, a == b returns True because their values match. However, a is b returns False because they reside at different memory addresses (id(a) != id(b)).
What is the return type of the built-in function input() in Python 3? A. int B. float C. str
D. bytes CORRECT ANSWER: C RATIONALE: The input() function reads line input from standard user interaction and always returns it as a string (str). If numerical processing is desired, explicit casting (e.g., int() or float()) must be applied.
What is the evaluated output of the expression not(5 > 2 and 10 < 5)? A. False B. True C. None D. TypeError CORRECT ANSWER: B RATIONALE: Evaluating the internal clause: 5 > 2 is True, while 10 < 5 is False. True and False yields False. Applying not negates False to True.
What format specifier or method is used in standard f-strings to format float val = 3.14159 to 2 decimal places? A. f"{val:.2}" B. f"{val:.2f}" C. f"{val:2f}" D. f"{val%2f}" CORRECT ANSWER: B RATIONALE: Standard f-string formatting syntax utilizes :.2f to round a float value to two decimal places. {val:.2} would limit total precision to 2 digits, giving 3.1. The specification :.2f explicitly requests fixed-point floating representation with 2 places after the decimal point (3.14).
C. Beta\nGamma D. Gamma CORRECT ANSWER: B RATIONALE: Conditional branching in Python executes the first condition that evaluates to True and immediately exits the block. Here, x > 20 is False. The code checks x > 10 (15 > 10), which evaluates to True. Python prints Beta and skips the rest of the elif and else branches.
In a Python while loop, what does the optional else block execute? A. Executes during every iteration alongside the loop body. B. Executes once when the loop condition evaluates to False, provided the loop was not terminated by a break statement. C. Executes only if an unhandled exception occurs inside the loop body. D. Executes immediately when a break statement is encountered. CORRECT ANSWER: B RATIONALE: A while or for loop's else clause executes when the loop condition evaluates to False naturally. If the loop is exited prematurely via a break statement, the else block is completely skipped.
What is the output of list(range(2, 10, 3))? A. [2, 3, 4, 5, 6, 7, 8, 9, 10] B. [2, 5, 8, 11] C. [2, 5, 8] D. [3, 6, 9] CORRECT ANSWER: C RATIONALE: The range(start, stop, step) function generates numbers beginning at start (2), incrementing by step (3), and stopping before reaching stop (10). The
sequence includes 2, 2+3=5, and 5+3=8. The next value 11 is $\ge 10$, so generation stops. The resulting list is [2, 5, 8].
What occurs when a continue statement is executed inside a loop? A. The entire loop is terminated immediately. B. The current iteration terminates immediately, skipping remaining statements in the block and advancing to the next iteration. C. The loop restarts from the very first item in the sequence regardless of current state. D. Execution halts until user input is received. CORRECT ANSWER: B RATIONALE: The continue statement skips the execution of the remainder of the loop body for the current iteration and returns control to the loop condition evaluation or next item iteration step. To terminate the loop entirely, break must be used.
Which statement regarding Python's pass keyword is accurate? A. It terminates the enclosing loop or function immediately. B. It acts as an alias for continue. C. It acts as a null statement (placeholder) that does nothing when executed. D. It skips execution of the parent class constructor. CORRECT ANSWER: C RATIONALE: pass is a syntactic placeholder in Python. It is used when code structure requires a statement block (such as an empty class, function, or if clause) but no operational code needs to run.
What is the result of executing the following snippet?
D. Infinite loop CORRECT ANSWER: C RATIONALE: Let's trace execution:
Given items = ["a", "b", "c"], how can a developer obtain both element index and item during loop iteration? A. for i in range(items): B. for i, item in zip(items): C. for i, item in enumerate(items): D. for i, item in items.items(): CORRECT ANSWER: C RATIONALE: The enumerate() built-in function takes an iterable and returns an enumerate iterator yielding tuples of (index, item). This allows access to both the loop counter index and item value during iteration.
What is short-circuit evaluation in Python logical expressions? A. Halting script execution when a math error occurs. B. Stopping logical evaluation as soon as the outcome is guaranteed (e.g., if the first argument of and is False). C. Casting logical expressions to integer values automatically. D. Optimizing loop steps during compile time.
RATIONALE: Python evaluates and and or expressions from left to right using short-circuit evaluation. For and, if the left operand is False, the overall result must be False, so the right operand is not evaluated. For or, if the left operand is True, evaluation stops immediately.
What is printed by the following code snippet?
val = 0 for i in range(5): if i == 3: break val += i else: val += 100 print(val)A. 103 B. 106 C. 3 D. 10 CORRECT ANSWER: C RATIONALE: Tracing loop iterations: