Select Page

Efficiency – 5 minutes

There’s no need to recreate the database every time we run our program. So let’s check whether the database exists and only create a database if it doesn’t exists.

We can start by renaming our setup_database() where it’s defined and where it’s called.

Pretty straightforward to do the bit of renaming. The next part is pretty straightforward too. We need to check whether the database file exists and then react accordingly, only creating the database if we need it.

We’ve added an if statement that uses a built-in Python function (os.path.exists()) to see whether the database file exists. If it does exist then we just print a little message on the screen. If it does not exist then we go through the same steps we had followed in our old setup_database()implementation.

Share This