Читать книгу Introduction to Python Programming for Business and Social Science Applications - Frederick Kaefer - Страница 55

Logic Errors

Оглавление

The third category of errors, logic errors, is often the most difficult to identify. A logic error occurs when a program executes without terminating with an error condition but produces incorrect results. Logic errors can result from using an incorrect operator in an equation or using parentheses in the wrong location. An example of Python code with a logic error is in Figure 2.12.

Description

Figure 2.12 Python Code with Logic Error


Figure 2.13 Output for Python Code with Logic Error

This example demonstrates how easy it is to develop code that executes but does not produce the correct results. Figure 2.13 prints out the message that the average of 4 and 8 is 8! The true average of 4 and 8 is 6 and results when you add the two numbers together prior to dividing the sum by 2. Reviewing the order of operations discussed earlier, we need to put parentheses around the addition of first_number and second_number to correct this error, which adds the numbers together first. As it is now (without those parentheses), we first divide second_number by 2 (resulting in the value 4) and then add that result to first_number (resulting in a final value of 8), which is incorrect. To ensure that code executes with the correct results, programmers need to develop test cases and verify that the expected outcomes for each test case do in fact occur.

Introduction to Python Programming for Business and Social Science Applications

Подняться наверх