liveBook · Manning

Logical error

As explained in Learn AI-Assisted Python Programming, Second Edition

A logical error is a program defect in which syntactically valid code computes an incorrect result or performs behavior that does not match its intended logic.

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

How Learn AI-Assisted Python Programming, Second Edition covers it

How deep it goes
Explains the mismatch, demonstrates a failing test, traces values with prints, and corrects the matching condition.
Examples
Uses a word-counting function that incorrectly counts “danger” alongside “Dan.”
What you can do after
Diagnose/debug with it by comparing expected output, inspecting intermediate values, locating the mismatch, and revising the condition.
How it connects
Connects logical errors with syntax errors, debugging, test cases, print statements, and prompt quality.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn AI-Assisted Python Programming, Second Edition. The section links point to the parts of the book it draws on.