A data analyst uses Python to process a CSV file containing sales data. The file has columns: 'Product', 'Price', 'Quantity'. The analyst writes a script to compute total sales: sum of Price * Quantity for each row. The code reads each row as a list of strings. The analyst uses: total = 0; for row in reader: total += row['Price'] * row['Quantity']; print(total). The script raises a TypeError. What is the best fix?
Correct: uses integer indices to access list elements and performs float conversion, resolving both the key error and the string multiplication error.
Why this answer
The TypeError occurs because row is a list of strings, so integer indices must be used instead of string keys. Multiplying strings also requires conversion. Option D correctly uses float(row[1]) * float(row[2]) with indices, fixing both issues.
Option A only converts to float but still uses invalid string keys.
Exam trap
Python Institute often tests the distinction between string repetition (valid) and string multiplication of two strings (invalid), leading candidates to overlook the need for explicit type conversion.
How to eliminate wrong answers
Option B is wrong because it still uses string indices (reader[i][1] and reader[i][2]) without conversion, so multiplication of strings still raises a TypeError. Option C is wrong because integer multiplication would fail if the data contains decimal values (e.g., '19.99'), and converting to float afterward does not fix the initial type error. Option D is wrong because it uses numeric indices (row[1], row[2]) instead of the column names 'Price' and 'Quantity', which would cause a KeyError if the CSV reader uses DictReader, or would access the wrong columns if the order differs.