1/29
Comprehensive practice flashcards covering fundamental Python concepts from Chapters 1 through 7 of PFP191, including variables, conditionals, functions, iterations, strings, file handling, and lists.
In Python, what is the difference in output between the regular division operator / and the floor division operator //?
Regular division (/) always performs float division and returns a float (e.g., 7/2 evaluates to 3.5), whereas floor division (//) rounds down to the nearest integer towards negative infinity (e.g., 7//2 evaluates to 3 and −7//2 evaluates to −4).
What is the associativity of the exponentiation operator ** in Python, and what is the evaluation result of 2 ** 3 ** 2?
Exponentiation associates from right to left. Therefore, 2∗∗3∗∗2 is evaluated as 2∗∗(3∗∗2)=2∗∗9=512.
What is the result of evaluating -2 ** 2 in Python, and what causes this behavior?
The result is −4 because exponentiation (**) has higher operator precedence than unary negation (-). Python evaluates it as −(2∗∗2).
What data type does the built-in input() function always return in Python?
It always returns a string (str). If numeric operations are required, the return value must be explicitly converted using int() or float().
How does the int() constructor process a floating-point number such as 3.9?
It truncates the fractional part towards zero rather than rounding, returning 3.
What is the fundamental difference between the = and == operators in Python?
= is the assignment operator used to assign values to variables, whereas == is a comparison operator used to test equality between two expressions.
What is the order of precedence from highest to lowest among the logical operators not, and, and or?
The order of precedence from highest to lowest is not, followed by and, and then or.
What is short-circuit evaluation, and what is the result of evaluating False and (1/0 > 0)?
Short-circuit evaluation stops evaluating a compound boolean expression as soon as the overall truth value is determined. Because the left operand of and is False, the right operand is never executed, and Python safely evaluates the expression to False without raising a ZeroDivisionError.
In a Python try-except structure, when do the optional else and finally blocks execute?
The else block executes only when no exception occurs in the try block. The finally block executes unconditionally, whether an exception occurred or not.
What is the technical distinction between a parameter and an argument in Python functions?
A parameter is a variable listed inside the parentheses of the function definition (def), while an argument is the concrete value supplied to the function when it is invoked.
Why does a function signature such as def f(a=1, b): trigger a SyntaxError?
Python requires all parameters with default values to follow any parameters that do not have default values.
What value is returned by a Python function that does not include an explicit return statement?
It implicitly returns None.
What composite data type is returned when a function executes a statement like return 7, 2?
It packs the multiple values and returns them as a tuple.
What essential structural element must be present in a recursive function to prevent an infinite loop?
A base case (stopping condition) that terminates further recursive calls.
Under what circumstance is a while loop typically chosen over a for loop?
A while loop is preferred when the exact number of iterations is unknown in advance and depends on a dynamic condition, whereas a for loop is ideal for iterating through a known sequence or collection.
What list is produced by evaluating list(range(2, 6))?
It produces [2,3,4,5], because the stop value 6 is non-inclusive.
How do the break and continue loop control statements differ in behavior?
break terminates the surrounding loop completely, whereas continue aborts only the remainder of the current iteration and jumps directly to the next iteration.
When does the else block associated with a for or while loop execute?
The else block executes only when the loop terminates normally by exhausting its sequence or making its condition false, and is skipped if the loop is terminated by a break statement.
Why is initializing an accumulator variable to None preferred over 0 when finding the maximum value of a dataset?
If the dataset contains only negative numbers, initializing with 0 produces an incorrect maximum of 0, whereas None acts as a sentinel indicating that no elements have been inspected yet.
What does it mean that Python strings are immutable?
It means individual characters or slices cannot be modified in place. Any string manipulation method (such as .upper() or .replace()) produces a new string object rather than modifying the existing one.
What is the difference in behavior between slicing past the end of a string ('abc'[10:20]) versus direct indexing past the end ('abc'[10])?
Slicing beyond the bounds does not raise an error and evaluates to an empty string (''), whereas indexing beyond the valid range raises an IndexError.
How does the string .find() method handle a missing substring compared to the .index() method?
The .find() method returns −1 when the target substring is not found, whereas .index() raises a ValueError.
What are the behavioral differences between file modes 'w', 'a', and 'x' in Python's open() function?
'w' opens a file for writing and truncates (clears) existing content; 'a' opens a file for appending new data to the end without modifying existing data; and 'x' creates a new file exclusively, raising an error if the file already exists.
What is the most memory-efficient pattern for processing a very large text file line-by-line?
Iterating directly over the file object using for line in f:, which loads lines lazily one at a time instead of reading the entire file into memory.
What primary benefit does using the with open(...) as f: context manager provide over manual file closing?
It guarantees that the file handle is automatically and properly closed upon leaving the block, even if runtime exceptions are raised.
What is the difference in operation and return value between list.sort() and the built-in sorted() function?
list.sort() sorts the list in place and returns None, mutating the original list. In contrast, sorted() leaves the original list unchanged and returns a new sorted list.
Given a = [1, 2], what is the difference between writing b = a versus b = a[:] when subsequently running b.append(3)?
b = a creates an alias referencing the exact same list object, making a equal to [1,2,3]. b = a[:] creates a shallow copy, leaving a unchanged as [1,2].
Why does initializing a matrix with [[0] * 3] * 3 introduce a logical hazard?
Multiplying the outer list creates three references pointing to the exact same inner list object. Mutating an element in one row will unintentionally mutate every row. The list comprehension [[0] * 3 for _ in range(3)] should be used instead.
What is the difference in effect between a.append([2, 3]) and a.extend([2, 3]) on the list a = [1]?
a.append([2, 3]) inserts the entire sublist as a single element ([1,[2,3]]), while a.extend([2, 3]) unpacks and appends each element individually ([1,2,3]).
What is the difference between the is operator and the == operator in Python?
== checks for value equality (whether two objects contain the same data), while is checks for object identity (whether two references point to the exact same location in memory).