Computer Science – 12.3 Program Testing and Maintenance | e-Consult
12.3 Program Testing and Maintenance (1 questions)
Error Identification: The error is in the comparison within the if statement. The code uses if number largest:.
Effect on Output: Because the code is comparing for numbers *less than* the current largest, it will never update the largest variable if a larger number is encountered. The function will always return the first element of the list as the largest, even if other elements are larger.
Example: If the input list is [3, 1, 4, 1, 5, 9, 2, 6], the expected output is 9. However, the current code will return 3, because it starts by assuming the first element (3) is the largest and never updates it to a larger value.
Corrected Code:
def find_largest(numbers):
largest = numbers[0]
for number in numbers:
if number > largest:
largest = number
return largest