Consider the following code snippet that calculates the sum of numbers from 1 to 5 but has a subtle bug. What will be the output?
total = 0 for i in range(1, 6): total += i print(total)
Remember that range(1, 5) includes numbers from 1 up to but not including 5.
The range(1, 6) generates numbers 1, 2, 3, 4, 5. Their sum is 15, so the output is 15.
What is the most likely cause of the following error message when running this code?
IndexError: list index out of range
Code snippet:
numbers = [10, 20, 30] print(numbers[3])
numbers = [10, 20, 30] print(numbers[3])
Check the list length and the index used.
The list has 3 elements indexed 0, 1, 2. Accessing index 3 is out of range, causing the error.
Which debugging approach is best to find why a program calculating average scores gives wrong results?
Think about how to find where the calculation goes wrong step-by-step.
Adding print statements helps observe values during execution to locate the logic error.
What type of bug is present in the following code?
def divide(a, b):
return a / b
result = divide(10, 0)
print(result)def divide(a, b): return a / b result = divide(10, 0) print(result)
What happens when dividing by zero in Python?
Dividing by zero causes a runtime error called ZeroDivisionError.
Given the following code, what will be the output or error?
def process(data):
total = 0
for i in range(len(data)):
total += data[i]
return total // len(data)
values = [10, 20, '30', 40]
print(process(values))def process(data): total = 0 for i in range(len(data)): total += data[i] return total // len(data) values = [10, 20, '30', 40] print(process(values))
Check the data types inside the list and how addition works.
Adding an integer and a string causes a TypeError at runtime.