Errores - johncroth/pythonEd2024 GitHub Wiki

Finding and fixing errors is a key activity for any programmer.

  • Approximately, when writing code, professional programmers make 2 corrections in every line of code they write.
  • Even so, on average, 7 out of 100 lines have errors when they submit code to their teams.
  • Between 5 or 6 of these errors are repaired after testing.
  • This leaves 1 or 2 errors in every 100 lines of code for the client to deal with.
  • This rate of errors has been the same, over the entire history of programming, despite much effort.

Fortunately, Python helps us find and fix errors. To see how, copy and paste this simple program into a file "errors_a.py":

print( "Hola mundo" )
print( Que tienes? )
print( "Cual es tu problema?' )

Save the file and run the program. You should see a message a lot like this:

 File "c:\users\johnc\mu_code\errors_a.py", line 2
    print( Que tienes? )
               ^
SyntaxError: invalid syntax

Unfortunately, these messages are almost always in English and this is not likely to change. However, you can notice a lot with only a little knowledge of English.

  1. You are told the error occurred in line 2.
  2. There is a pointer to where python gave up trying to understand the program.
  3. There is a message describing the type of error, here a "SyntaxError". This is a common error--it means the code does not conform to Python's most basic requirements.

The exact problem is that what one puts in a print statement needs to be in either quotes or quotation marks. So change line 2 to

print("Que tienes?")

then save the file and runt it again.

Now, I see 2 lines printed out, as well as the following error message:

File "c:\users\johnc\mu_code\errors_a.py", line 3
    print( "Cual es tu problema?' )
                                  ^
SyntaxError: EOL while scanning string literal

According to the message, the problem is near the end of line 3. We notice that we started the message with quotation marks and ended the message with a single quote; that doesn't work. So change the ' to a " and run the program again. You should see the three lines printed out.

As programs get more complicated, your errors mat get harder to understand. But the first step is always to read the error message and look for the line number(s) and other hints in the error message.

Exercises

  1. Copy the following program into the file "errors_1.py". Run it, then find and fix the errors in each line, one by one. Run the program again after each line.

TODO the program. TODO decide place in the lesson plan first.

  1. Copy the following program into the file "errors_2.py". Run it, then find and fix the errors in each line.