Kyle Banks

Get Started Programming with Python

Written by @kylewbanks on Feb 18, 2013.

Getting Started

First off, lets get Python installed. If you are running a Linux distro you should already have it on your system. Run the command:

python -V
In a terminal to see if you have it. If not take a look around for how to properly install it on your system. Many Linux distros rely on Python, and a specific version at that, so you have to be careful not to ruin your OS's installation.

If you do want to use a different version of Python on Linux, you will need to modify the PATH variable to point to your installation. It is highly recommended you do NOT modify the 'default' Python installation. Again, take a look around for notes on how to install Python on your distro.

If you are using Windows or Mac OS, Python can be downloaded here. I recommend getting Python version 3.2.X or higher. Download the appropriate installer for your system, and run it while following the prompts.

Hello, Python!

Let's start our Python careers with the usual "Hello, World!" tutorial. Don't worry, we will write something a little more complex shortly.

If you are on Linux, simply type

python
into a terminal to open the interactive Python shell. This shell can be used to great affect for testing your code or trying out different methods and classes.

If you are on Windows, lets open up IDLE, the IDE installed by default with Python. (This IDE is also available to Linux, but does not come with the default installation). Click Start -> All Programs -> Python X.X -> IDLE (Python Gui) to open up a similar Python shell as Linux users are seeing.

Now that we have our shell open, let's say hello to the world.

print("Hello, World!")

Wait... what? No semi-colon? No class or method declarations? No imports? Well, that was easy! As you can see, python code is written without semi-colons (unless you want to), and uses whitespace as it's main syntactical means of determining when you have finished typing a command. The only time you have to use the semi-colon is if you want to put two or more commands on the same line. For instance

# This won't work...
print("Hello, World") print("What a fine day to learn Python!")

will not work. You would need to put a semi-colon after the first print statement. However if you like to maintain your sanity, you likely aren't writting multiple statements on one line in the first place. In this case, you will never need to use the semi-colon in Python. Hooray!

Integers & Basic Mathematics

What good is programming without numbers? Let's try out a more complicated Python application, and make a calculator.

First thing's first, we need to define what our calculator will need. We want to be able to read-in user input, convert it into an integer, perform addition, subtraction, multiplication or division, and output a result. We should be able to handle a case where the user does not input an integer, and if they try to divide by zero. This should be enough requirements to get us started, and to build a good introductory Python program.

If you are running linux, open a new file in your favorite text editor and save it as python_calculator.py in a location that you won't lose it.

On Windows, open IDLE if you already closed it, and select File -> New Window. This will open up a blank window we can use for editing code, and we can run our code from here in the Python shell. Save this file as python_calculator.py.

The first thing we are going to do is quickly document our program using Python's multi-line comments.

"""
Simple calculator application.

Reads input from the command line, performs operations, and outputs a value.
"""

As you can see, in Python the multi-line comments are done using three double-quotes. We will take a look at the single line comments a little later.

Next up, we want to ask the user to provide their first number. We can do this using the input() function which takes an optional string to prompt the user. We also want to convert this input to an integer so that we can perform operations on it.

num1 = int(input("Enter a number: "))

Note that this is not safe. If the user were to enter a non-numeric value, the program would throw an exception. We can fix this using a try-catch block.

try:
    num1 = int(input("Enter a number: "))
except NameError:
    print("You have entered an invalid number!")

There are a few things to pay attention to here. The first thing is that lines inside a try-block (or if-statement, while-loop, etc.) must be indented. Python uses whitespace as syntax, so you need to make sure to use the same amount of whitespace for each line. If you are using a tab, always use a tab. If you use 3-spaces, always use 3-spaces. Fixing whitespace errors can be troublesome so it's important to train yourself early to maintain consistent spacing.

The second thing to note is that the lines that are indented are preceded by a line with a colon. This colon acts like braces do in many other languages. The colon tells Python that the following indented lines should only be executed if the preceding statement evaluates to True.

Now back to our calculator. If the user enters a non-numeric value, the application will catch the NameError exception and output an error message. Let's try it out.

On Linux (ensure your PATH variable points to the correct Python installation):

python python_calculator.py

On Windows, click Run -> Run Module or F5

If you enter an invalid number, you should see something like this:

Enter a number: Five
That is not a valid number!

Otherwise, the program should exit gracefully without doing anything.

Note there is still one problem with this piece of code. We don't want the program to exit if the user inputs bad data, we want it to prompt for input again. We can use a while-loop to help us out with this. Edit your code to look like this:

while True:
    try:
        num1 = int(input("Enter a number: "))
        break
    except NameError:
        print("You have entered an invalid number!")

This will loop until the user inputs a proper integer. If they do not, it will output our error message, and prompt again.

Functions & Reusable Code

We are going to be asking for another number from the user, and we don't want to have to rewrite the same code multiple times, so why don't we create a function to accomplish this. We should be able to pass the function a string to prompt the user, and then it should return the value the user inputs.

Functions in Python are defined using the def keyword and must be defined previously in the code before they can be called. Let's modify our application to look like this:

# Prompt the user to enter a number, and return it
def askForNumber(prompt):
    while True:
        try:
            num = int(input(prompt))
            return num
        except NameError:
            print("That is not a valid number!")

# Application logic
num1 = askForNumber("Enter a number: ")

As you can see the code inside askForNumber is almost the same as what we wrote before, but now we don't have to write it again. We have created a reusable piece of code, rather than repetition. Here you can also see single line comments, preceded by the hash-symbol.

Next up we are going to want to ask the user for their second number. Now that we have this function, we can easily write this at the bottom of our code, and we now have two numbers from the user to work with:

num2 = askForNumber("Enter a second number: ")

Now lets output the results of a few mathematical operations. Beneath the code we currently have, add:

print("")
print(str(num1) + " + " + str(num2) + " = " + str(num1+num2))
print(str(num1) + " - " + str(num2) + " = " + str(num1-num2))
print(str(num1) + " / " + str(num2) + " = " + str(num1/num2))
print(str(num1) + " * " + str(num2) + " = " + str(num1*num2))

The first line simply prints a blank line for formatting. The remaining lines will compute the values of various operations, and convert the results into strings (as well as the original values) and print them to the user.

Sample output should look like this:

Enter a number: 23
Enter a second number: 2

23 + 2 = 25
23 - 2 = 21
23 / 2 = 11
23 * 2 = 46

Note that there are a few problems with our current code. One, if you try to divide by zero an exception is thrown. Try on your own to catch this exception and print your own error message to the user informing them that they almost caused their computer to implode.

The second issue is that if you input a floating point value, or when dividing uneven numbers, the result is a floating point number cast into an integer. Look at the output above again, and notice that 23 / 2 is not 11, its 11.5. The decimal places are missing! Try to rewrite this code to handle floating point values.

If all of this was too basic for you, or you have a little Python experience under your belt already, try getting started using Python GUI classes and create a calculator using GUI elements including buttons and textfields.

For now, here is the entire application code:

"""
Simple calculator application.

Reads input from the command line, performs operations, and outputs a value.
"""
# Prompt the user to enter a number, and return its value
def askForNumber(prompt):
    while True:
        try:
            num = int(input(prompt))
            return num
        except NameError:
            print("That is not a valid number!")

# Main logic
num1 = askForNumber("Enter a number: ")
num2 = askForNumber("Enter a second number: ")

print("")
print(str(num1) + " + " + str(num2) + " = " + str(num1+num2))
print(str(num1) + " - " + str(num2) + " = " + str(num1-num2))
print(str(num1) + " / " + str(num2) + " = " + str(num1/num2))
print(str(num1) + " * " + str(num2) + " = " + str(num1*num2))
Let me know if this post was helpful on Twitter @kylewbanks or down below!