A logical error occurs when valid code does something different from what the programmer intended. Unlike a syntax error, it usually runs without an error message, but produces the wrong result or behavior. section 8.1 section 8.2.1
Counting the exact word
A function intended to count the exact word “Dan” instead checks whether “dan” appears anywhere, ignoring case. With ["Dan", "danger", "Leo"], it returns 2 instead of 1 because it counts “danger.” section 8.1
Debug a logical error by narrowing the mismatch:
- Run a test case whose expected result is clear. section 8.2.1
- Print values at useful points, especially where the suspicious result changes. section 8.2.1
- Use the observed failure to revise the code or give Copilot a more precise prompt. section 8.1
Listing 8.2 Example of a print statement to find the bug
def count_words(words):
count = 0
for word in words:
if "dan" in word.lower():
print(word,"is being counted") #1
count += 1
return count
Shows where to place a print statement so the program reveals which words it is counting. section 8.2.1
