We have successfully set up and installed a LAMP server on our Ubuntu machine, optimized our server, and now it’s time to write our first Python application. We won’t be writing anything too fancy, but we will cover the basics of a Python application, and also talk a bit to either our MySQL or PostgreSQL database.

Throughout this tutorial, I will be using the nano editor in the terminal to write my Python code, but feel free to use whichever editor you please. It should not affect the outcome of this tutorial.

Python uses whitespaces. via Udacity

Also note that unlike many popular programming languages, Python uses whitespace indentation as a delimiter for code blocks, instead of the traditional curly braces or keywords. This allows Python to have extremely readable code, and forces you not to write single-line functions. Keep this in mind as you are writing your own program, as you don’t want to have issues caused by missing line breaks or indentation.

Creating Our First .py File

Navigate to a folder that you would like to create your first Python file in, and create a file called test.py. Now open this file up in the editor and type the following code:

print "Hello, World!"

Save your file, and in the terminal, navigate to wherever you created this file, and run it by calling python test.py. You should see the correct output:

This is a very simple way to write a Python application and see the result. However, what if we want to run the application without typing python test.py every single time? To do that, we can add the following to our code:

#!/usr/bin/python
print "Hello, World!"

That top line allows the file to locate the Python interpreter (which, by default, is in the /usr/bin/ folder). Save the file. Now we need to change the permission of this file so that it is executable by the terminal. Run the following:

chmod +x test.py

Now we can run the program by simply typing:

./test.py

Now, let’s add a variable to our program, as well as a conditional statement. What we want the variable to do is hold our first name (you’ll want to change the name used in this example to your own), and then our conditional statement will check to see whether the name is correct. If it is, the program will say hello. If it isn’t, the program will ask for the correct name.

#!/usr/bin/python

name = "Keenan"

if name == "Keenan":  
  print ("Hello,", name)
else:  
  print "Oh, well what is your name then?"

Let’s run our program and see the output.

You should see something similar to the above. Now let’s edit our program and misspell the name to see whether our condition is really working:

name = "Keenann"

Run the program again, and you should see:

Now we know that the conditional statement is checking the name, and if it’s different from the expected value, the program will ask for the correct name.

Writing a Simple Function

Let’s take our basic conditional statement and turn it into a function. We’ll write our function with a single argument that will be used to store our name. The program will then ask our user whether the name is correct, and the user can answer yes or no (inside of the terminal). Depending on whether the name is correct or incorrect, the program will display a different message.

#!/usr/bin/python

  def checkName(name):  
    checkName = input("Is your name " + name + "? ") 
    
    if checkName.lower() == "yes":    
      print("Hello,", name)  
    else:    
      print("We're sorry about that.")

checkName("Keenan")

You can define your function by using the def keyword, followed by a name for your function (in this example, it’s called “checkName”). Inside of our function, we declare a single argument, which allows us to input information into the function to be used. After that, we ask our user whether the name is correct, which can be accomplished by using the input method in Python.

Next, we write a conditional similar to the one above, checking to see whether the name entered is correct. If it is, we welcome the user. If it’s not, we apologize. The first line of the conditional has the biggest change, and that’s because we are checking what the user has typed in (via the checkName object) to see whether it was yes or no. We also force the user’s input to be lowercase, so that no matter how they type in “yes” (whether it’s yes, YES, yEs, or Yes), it will always be compared the same way.

At the end of our file, we are simply running the function we just created, and passing in our name as the parameter.

We should now be able to run our script and walk through both conditionals:

Let’s take our function a step further and allow our somebody to enter their name if it’s not the one the program expected. This will only take one additional line and one changed line.

#!/usr/bin/python3

def checkName(name):
  checkName = input("Is your name " + name + "? ") 
  
  if checkName.lower() == "yes":    
    print("Hello,", name)  
  else:    
    name = input("We're sorry about that. What is your name again? ")    
    print("Welcome,", name)

checkName("Keenan")

All of our changes lie right after our else: statement. Instead of just apologizing to the user, we assign a new value to our name parameter, which will both apologize and capture the new name for our user. Afterwards, we welcome our new user.

Running the application should look something like:

Creating MySQL Tables and Accessing Them

Now that we’ve written a simple function and used variables, user input, and conditional statements, let’s connect to our MySQL database (installed previously) to store and retrieve information.

Before we start writing any code, we need to ensure that a MySQL driver is installed on our machine. We’ll do this by running the following command:

sudo apt-get install python-mysqldb

However, before we add any Python code to actually interact with MySQL, we need to create a database table. Let’s run MySQL in our terminal (you will have to enter your root MySQL password afterward):

mysql -u root -p

Now let’s create a database in MySQL named “python”:

CREATE DATABASE python;

Let’s ensure that we’re connected to our new database in the terminal:

connect python

Now let’s create a table called “users” with one field for an auto-incrementing ID and one field for a first name:

CREATE TABLE users (
  id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
  firstname VARCHAR(30) NOT NULL
);

Your terminal should look similar to this:

mysql-create-tables.png

Now that we have our database and tables, let’s set up our Python script so we can access and modify it.

Opening up test.py, we should add the following code to our file:

#!/usr/bin/python
import MySQLdb

# Setup MySQL Connection
db = MySQLdb.connect(host="localhost", user="root", passwd="YOURPASSWORD", db="python")
cursor = db.cursor()

# Insert a row into our table
cursor.execute("INSERT INTO users (firstname) VALUES ('Keenan')")

# Save changes to database
db.commit()

You can see that after we declare our Python path, we import the Python-MySQLdb tool that we installed earlier. This is necessary so our program can interact with our MySQL database. Our next line is creating an object named db that stores our connection to MySQL. Ensure that each field here uses your correct host, username, password, and database (although the only thing that should be changing on your end is the password).

Next, we create an object named cursor that allows us to actually execute queries in MySQL. After that, we use the cursor object we just created and run a MySQL command to insert a row into the users field. In this case, I’m inserting my first name into the firstname field. We then call db.commit() to ensure that all changes we make to our database are saved.

Now if we save our file and run the following command inside of MySQL in our terminal, we should see:

connect python
SELECT * FROM users;

This means that we have successfully inserted a row into our users table in our database. We now know that our Python application is talking to MySQL.

Creating PostgreSQL Tables and Accessing Them

If we want to interact with a PostgreSQL (abbreviated throughout the article as “Postgres”) database, we will need to install and use a tool call psycopg2. We can do that by typing the following into the terminal:

sudo apt-get install python-psycopg2

We need to run Postgres inside of the terminal so that we can create and access our tables, but we need to create a Postgres user first. We’ll do that by first logging in as the default Postgres user:

sudo su - postgres

Now let’s create a Postgres database named “python”:

createdb python

Let’s ensure that we’re connected to our new database in the terminal:

psql -d python

We now need to create a new user and add them to the database so we can execute commands:

CREATE USER keenan WITH PASSWORD 'password';GRANT ALL PRIVILEGES ON DATABASE "python" to keenan;

Now let’s create a table called “users” with one field for an auto-incrementing ID and one field for a first name:

CREATE TABLE "users" ( 
  id SERIAL PRIMARY KEY, 
  firstname VARCHAR(30) NOT NULL 
);

Your terminal should look similar to this:

Now that we have our database and tables, let’s set up our Python script so we can access and modify it.

Opening up test.py, we should add the following code to our file:

#!/usr/bin/python 
import psycopg2  

# Setup PostgreSQL Connection 
db = psycopg2.connect("host=localhost dbname=python user=keenan password=YOURPASSWORD")
cursor = db.cursor()

# Insert a row into our table 
cursor.execute("INSERT INTO users (firstname) VALUES ('Keenan')") # Save changes to database db.commit()

You can see that after we declare our Python path, we import the Psycopg2 tool that we installed earlier. This is necessary so our program can interact with our Postgres database. Our next line is creating an object named db that stores our connection to Postgres. Ensure that each field here uses your correct host, username, password, and database (although the only thing that should be changing on your end is the password).

Next, we create an object named cursor that allows us to actually execute queries in Postgres. After that, we use the cursor object we just created and run a Postgres command to insert a row into the users field. In this case, I’m inserting my first name into the firstname field. We then call db.commit() to ensure that all changes we make to our database are saved.

Now if we save our file and run the following command inside of Postgres in our terminal, we should see:

su - postgres
psql python << EOF

SELECT * FROM users;
EOF

This means that we have successfully inserted a row into our users table in our database. We now know that our Python application is talking to PostgreSQL.

The Finish Line

Congratulations, you now have a very simple Python application that is communicating with your database, storing variables, getting user input, and running conditional statements. You could further expand your program by asking the user their name and storing that in the database, and possibly adding more complexity to your database.