Non-Programmer's Tutorial for Python 3/Dealing with the imperfect

closing files with with
We use the "with" statement to open and close files.

If some sort of error happens anywhere in this code (one of the files is inaccessible, the parse function chokes on corrupt data, etc.) the "with" statements guarantee that all the files will eventually be properly closed. Closing a file just means that the file is "cleaned up" and "released" by our program so that it can be used in another program.

catching errors with try
So you now have the perfect program, it runs flawlessly, except for one detail, it will crash on invalid user input. Have no fear, for Python has a special control structure for you. It's called  and it tries to do something. Here is an example of a program with a problem:

Notice how when you enter  it outputs something like:

Traceback (most recent call last): File "try_less.py", line 4, in    number = int(input("Enter a number: ")) ValueError: invalid literal for int with base 10: '\\@#&'

As you can see the  function is unhappy with the number   (as well it should be). The last line shows what the problem is; Python found a. How can our program deal with this? What we do is first: put the place where errors may occur in a  block, and second: tell Python how we want  s handled. The following program does this:

Now when we run the new program and give it  it tells us "That was not a number." and continues with what it was doing before.

When your program keeps having some error that you know how to handle, put code in a  block, and put the way to handle the error in the   block.

Exercises
Update at least the phone numbers program (in section Dictionaries) so it doesn't crash if a user doesn't enter any data at the menu.