Select Page

Python is one of the fastest-growing programming languages across the world. Given its incredible versatility, Python can solve many types of software problems. With that said, it shouldn’t come as a surprise that Python is an indispensable tool for data specialists, analysts, and machine learning engineers, among many other professionals.

In this article, we’ll walk you through writing your first Python application. In doing so, we’ll create a simple Python program covering rudimentary Python syntax before connecting the program to a database. Let’s get started.

Why Learn Python

Python is a powerful and in-demand programming language. In recent years, the language has been steadily climbing RedMonk’s “annual programming language rankings,” a list based on rankings from GitHub and StackOverflow. As of the January 2021 rankings, Python was in second place — one spot higher than the year prior.

There are many reasons for Python’s success, including the language’s remarkable versatility and simplicity. Python is a great programming language to learn first due to its intuitive syntax that resembles that of the English language and a relatively shallow learning curve.

Although Python has established itself as the standard language of artificial intelligence and data science, it’s also widely used in web development, scientific computing and software development. What’s more, Python boasts a vast community of collaborators who constantly enrich its already vast ecosystem and keep its many libraries up-to-date.

All of these reasons make Python a great starting point for any aspiring programming. Without further ado, let’s start writing our first Python program.

Creating Our First .py File

All Python files end with the “.py” extension. You can create, edit, and save with Python files with any text editor. 

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

print("Hello, World!")

Save your file, and in the terminal, navigate to the file’s location. Then, run the file by calling python test.py. This line instructs your Python interpreter to execute the command you just wrote. You should see the correct output:

Hello, World!

This hello-world program works, but let’s make it more interesting.

To start, let’s add a variable and a conditional statement to our program. We want the variable to store our first name — that we’ll provide to the program dynamically, and the conditional statement to check if the name provided matches the one we defined in the program. Depending on the result of the conditional statement, the program will print out a greeting message or ask for another name.

Note that unlike many other 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. Keep this in mind as you write your program. It will help you avoid issues caused by missing line breaks or indentation.

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:

Hello, Keenan

As the next step, let’s edit the name variable to store another name to see whether our condition is really working:

name = "Brian"

If you run the program again, you should see the following output:

Oh, well, what is your name then?

As expected, since the two names are not the same, the program executes the statement captured by the “else” branch of the condition.

Writing a Simple Function

Let’s take our basic program logic and turn it into a function. 

Our function will accept a single argument called “name.” The program will then ask whether the provided name is the name of the person interacting with the program. The user may answer affirmatively with a “yes,”that will prompt the program to print a greeting message. Any other answer will be interpreted as negative and the program will thus print another message.

This function might be implemented in the following way:

def checkName(name):  
    answer = input("Is your name " + name + "? "


    if answer.lower() == "yes": // lower() turns the answer into lowercase
        print("Hello,", name)  
    else:    
        print("We're sorry about that.")

checkName("Keenan")

Let’s examine this new program component by component.

We begin by defining the function (if this part is confusing, check out our article on function definition in Python). In short, Python functions are prefaced using the def keyword followed by the function’s name; in this example, we’ll call our function checkName

Inside the function, we declare a variable answer. Using Python’s input method, we ask the user whether the name being printed out is theirs and the user provides their answer by typing it into the terminal. We store the answer into a variable and perform the conditional check.

Note that the conditional now calls the lower() method on the answer. We use this method simply to ensure that the answer is lowercase so that it’s always evaluated identically regardless of how the user types it in — whether as “yes,” “YES,” “yEs” or “Yes.” 

At the end of the file, we call the function, passing our name as the parameter. With this function call in place, we should be able to run our script and walk through both conditionals:

Is your name Keenan? No
We're sorry about that.

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

def checkName(name):
    answer = input("Is your name " + name + "? ") 

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

checkName("Keenan")

The new changes are right after the “else” statement. Instead of apologizing to the user, the program now asks for the user’s name and greets them. Running the program should look something like this:

We're sorry about that. What is your name again? Lisa
Welcome, Lisa

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

Creating and Accessing MySQL Tables 

Before we start writing any code, we need to ensure that a MySQL driver is already installed on our machine. To install MySQL, you may follow the instructions in this blog post.

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

mysql -u root -p

As the next step, let’s create a database in MySQL named “python:”

CREATE DATABASE python;

Once the database is created, we create a connection to our new database in the terminal:

connect python

With the connection established, we are able to create a table called “users,” with one field for auto-incrementing IDs and another for first names:

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

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

Let’s open up the test.py file and add the following code:

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()

First, we import the Python-MySQLdb tool that allows our program to interact with our MySQL database. The line below it then creates an object named db, which stores our connection to MySQL. Ensure that each field here uses your correct host, username, password and database.

Next, we create an object named cursor that allows us to 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, we insert the name “Keenan” into the firstname field. We then call db.commit() to ensure that all changes we make to our database are saved.

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

connect python
SELECT * FROM users;

We should see the following:

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 and Accessing PostgreSQL Tables

If we want to interact with a PostgreSQL (“Postgres”) database, we’ll need to install and use psycopg2. You can find the installation instructions on psycopg2’s website.

Once you’ve installed Postgres, type in the command below in your terminal to run the program, replacing “yourUserName” with the name of your user account:

psql -U yourUserName -h localhost dbname

Next, create a Postgres database named “python”:

createdb python

To ensure that we’re connected to our new database in the terminal, we can run the following command:

psql -d python

The next step is 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;

With the user provisioned, we can create a table called “users” with one field for auto-incrementing IDs and another for first names:

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

Your terminal should look similar to this:

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

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

import psycopg2  

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

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

We first import psycopg2 so that our program can interact with our Postgres database. In the line below, we then create an object named db that stores our connection to Postgres. Make sure that the fields correspond to the correct host, username, password and database.

Next, we create an object named cursor that allows us to 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. With that done, we insert the name “Keenan” into the firstname field. We then call db.commit() to ensure that all changes we make to our database are saved.

Let’s save our file and run the following command inside of Postgres in our terminal:

su - postgres
psql python << EOF

SELECT * FROM users;
EOF

Our terminal should look somewhat like this:

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

Learn To Code With Udacity

Congratulations, you’ve just built a simple Python application that’s communicating with your database, storing variables, getting user input and running conditional statements. You could expand your program by asking the user their name and storing it in the database.

If you want to learn more about how to write a Python application, consider enrolling in a Udacity Nanodegree program, where you’ll complete hands-on projects and get valuable career support. We offer an Introduction to Programming program, which is great for beginners to HTML, CSS, JavaScript and/or Python. If you’re particularly interested in Python, check out our Python for Data Science program, which provides a more specialized approach to mastering the language.

Enroll in our Introduction to Programming Nanodegree program today!