Exceptions

In any programming, including Python, exceptions and error handling often becomes a necessity when you are dealing with a considerable amount of variables. When, I say variables I do not mean variables as a placeholder, but variables as in you are using file system processes (like reading a file), dealing with external input, etc. Sometimes, you just do not know what will be thrown at your code. So you being little genius, you plan ahead and use exceptions and error handling where appropriate. Typically, the goal is to execute the code as intended, but if an exception occurs, we would prefer Python not to spit out its own exceptions. Instead, we would like to inform the user what went wrong using our wording and possibly how they can maneuver around the obstacle.

Exceptions vs Errors

I know I keep babbling about exceptions and errors, but what in the heck are they and how are they different you might ask. Well, exceptions generally deal with small little issues that you would probably like to handle. For example, maybe you do not exactly know the type of the variable, but you would definitely like to do something with it. The differences in doing things with numbers and strings are pretty different. So, you might set up something like this:

Example
var1 = '1'
try:
    var1 = var1 + 1 # since var1 is a string, it cannot be added to the number 1
except:
    print(var1, " is not a number") #so we execute this
print(var1)

Awesome! We totally caught the exception that python gave us. We simply put the code we wanted to execute under the try block. However, if an exception occurred (adding a string to and integer is an exception) we told Python to do everything in the except block.

So, what are errors? Bad news, that’s what they are. You normally do not want to handle errors, unless you are doing some dangerous things. When an error is generated, it typically means Python is blowing up the ship, Obviously, if the ship is blown up, we should jump ship and get out of the program.

Also, you might have noticed that the print() takes two arguments in this example. Well, it can take as many arguments as you want to give it. print() will keep on printing all of your arguments with a space in between them.

Elegant Error Handling

Let’s face it our try/except above, doesn’t do a whole lot for the usability of the program. Basically, if it messes up it just tells our users what is wrong. What is the point in that? We should attempt to handle our exceptions in a manner that helps the program to keep moving on. A better alternative would be something like this:

Example
var1 = '1'
try:
    var2 = var1 + 1 # since var1 is a string, it cannot be added to the number 1
except:
    var2 = int(var1) + 1
print(var2)

Ah, much better. In this example, we use our simple except to catch an exception. But, if you run the example, you will see something much more awesome happening. We actually catch the exception, and tell python, “Well, try casting it to an integer before adding”, where Python faithfully obeys. As the end result, Python prints out the number 2 and the user is none the wiser that the program had a small hiccup.

Overview

The Python tutorial is constructed to teach you the fundamentals of the Python programming language. Eventually, the Python Tutorial will explain how to construct web applications, but currently, you will learn the basics of Python offline. Python can work on the Server Side (on the server hosting the website) or on your computer.

However, Python is not strictly a web programming language. That is to say, a lot of Python programs are never intended to be used online. In this Python tutorial, we will just cover the fundamentals of Python and not the distinction of the two.

Python works much like the two previous categories, PHP and ColdFusion as they are all server side programming languages. You will see from the Python tutorials that it’s syntax is extremely different than the other two. It is probably the most clean and straightforward language you will ever learn.

Just like the other languages, Python is useful because it can dynamically generate content to provide a more customized user experience. Generally, Python is a great starting language for most people, but to others, it is extremely frustrating (primarily due to spacing issues), which is why I have put the Python Tutorial at the end of the server side languages.

Enough chatter!

We want to learn Python!

Tuples

In Python, tuples are almost identical to lists. So, why should we use them you ask? The one main difference between tuples and lists are that tuples cannot be changed. That is to say you cannot add, change, or delete elements from the tuple. Tuples might seem odd at first, but there is a great reason behind them being immutable. As programmers, we mess up occasionally. We change variables that we didn’t want to change, and sometimes, well, we just want things to be constant so we don’t accidentally change them later. However, if we change our minds we can also convert tuples into lists or lists into tuples. The fact is we need to make the conscious effort to say Python, I want to change this tuple into a list so I can modify it. Enough babbling, let’s see a tuple in action!

List vs. Tuple

Example
myList = [1,2,3]
myList.append(4)
print (myList)

myTuple = (1,2,3)
print (myTuple)

myTuple2 = (1,2,3)
myTuple2.append(4)
print (myTuple2)
Result [1, 2, 3, 4]
(1, 2, 3)
Traceback (most recent call last):
File “C:/Python32/test”, line 9, in
myTuple2.append(4)
AttributeError: ‘tuple’ object has no attribute ‘append’

So, we see that the list clearly works as expected. We just append a 4 onto the end, and Python doesn’t miss a beat. Next, we test out our tuple declaration and it works as well. But when we try to append to the tuple, Python give us a nasty little error. Like I said, you cannot change a tuple! Python will bite you if you try using things like append on a tuple. But, let’s say “Hey, I really want to add a four to that tuple.” Let’s do it:

Example
myTuple = (1,2,3)
myList = list(myTuple)
myList.append(4)
print (myList)
Result [1, 2, 3, 4]

Boom! We have successfully undone what Python was trying to teach us not to do. We just casted the tuple into a list, then once it was a list, we used it’s append method to add the 4. It should be reiterated that the purpose of a tuple is to be immutable. If you are planning to change the variable, just use a list instead.

Introduction

First, off Python usually requires some setup by downloading the Python IDLE. The Python IDLE is basically a text editor that lets you execute Python code. If you want to use Python as a server-side language, you certainly can. Python can output HTML just like other languages can, but Python is more commonly used as a module rather than intertwined like some PHP or ColdFusion. As for right now, I recommend you download the IDLE to help you debug your code while we learn the fundamentals offline. One really quick note, we are using python 3.2. Before we go to an example, please understand that Python is space sensitive. This means you must have 4 spaces for each indentation every single time. We’ll get into this more later, now let’s go to an example.

Example
print ("My first Python code!")
print ("easier than I expected")
Result My first Python Code!
easier than I expected

You can see right off the bat, that we use print() a whole lot. Basically, all it does is output whatever is inside the parentheses. You will be doing lots of printing so, you can get more comfortable with it as we go. Print is a function that we will go into later, but just understand that it can take a value. On the first line, we provide a string value “My first Python code!”, which is a string because of the quotes. So, you just told Python to output that string to the console. Python completes that task and moves onto the next line where it prints out a different string.

See how simple that was? Well, get used to it. Python is probably one of the simplest looking languages that can do some of the most powerful things you can imagine. You can see from the example how clean Python’s syntax is without all of the extra stuff that other languages add. That covers the easiest Python statement you will ever write. In the following sections, we will be using more advanced functions and teaching you the fundamentals of Python.

Reading Files

Many times, a programmer finds a reason to read content from a file. It could be that we want to read from a text file, such as a log file, or an XML file for some serious data retrieval. Sometimes, it is a massive task to figure out how to do it exactly. No worries, Python is smooth like always and makes reading files a piece of cake. There are primarily 2 ways in which Python likes to read. To keep things simple, we are just going to read from text files, feel free to explore XML on your own later. XML is a pretty cool markup, but as you get deeper, it is kind of a headache. Enough of my tangents, to the coding board:

Opening a File in Python

test.txt
I am a test file.
Maybe someday, he will promote me to a real file.
Man, I long to be a real file
and hang out with all my new real file friends.
Example
f = open("test.txt", "r") #opens file with name of "test.txt"

This is pretty simple to explain. We have our awesome little test.txt file filled with some random text. Now, in the example we have our code. Just like you click a file to open it, Python needs to know what file to open. So, we use the open method to tell Python what we want to open and to go ahead and open (make a connection to) it. The “r” just tells Python that we want to read (it is “w” when we want to write to a file). And, of course, we set this new connection to a variable so we can use it later. However, we have only opened a file, which is not all that exciting. Let’s try reading from the file.

Python File Reading Methods

  • file.read(n) – This method reads n number of characters from the file, or if n is blank it reads the entire file.
  • file.readline(n) – This method reads an entire line from the text file.
Example
f = open("test.txt","r") #opens file with name of "test.txt"
print(f.read(1))
print(f.read())
Result I
 am a test file.
Maybe someday, he will promote me to a real file.
Man, I long to be a real file
and hang out with all my new real file friends.

Woot woot! So, this might be a little confusing. First, we open the file like expected. Next, we use the read(1), and notice that we provided an argument of 1, which just means we want to read the next character. So, Python prints out “I” for us because that is the first character in the test.txt file. What happens next is a little funky. We tell Python to read the entire file with read() because we did not provide any arguments. But, it doesn’t include that “I” that we just read!? It is because Python just picks up where it left off. So, if Python already read “I”, it will start reading from the next character. The reason for this is so you can cycle through a file without have to skip so many characters each time you want to read a new character. It’s complicated, I know, but think of reading like a one way process. Python is lazy, it doesn’t want to go back and reread contents. Let’s take this one step further with reading lines.

Example
f = open("test.txt","r") #opens file with name of "test.txt"
print(f.readline())
print(f.readline())
Result I am a test file.
Maybe someday, he will promote me to a real file.

Ha! This time we were prepared for Python’s trickery. Since we just used the readline() method twice, we knew that we would get first 2 lines because of Python’s reading process. Of course, we also knew that readline() reads only a line because of it’s simple syntax. Alright, one last important, complicated, and awesome thing about Python’s reading abilities.

Example
f = open("test.txt","r") #opens file with name of "test.txt"
myList = []
for line in f:
    myList.append(line)
print(myList)
Result [‘I am a test file.\n’, ‘Maybe someday, he will promote me to a real file.\n’, ‘Man, I long to be a real file\n’, ‘and hang out with all my new real file friends.’]

What!? Python just blew our minds! First, don’t freak out with the \n. It is just a newline character, since those lines are on a different file, Python wants to keep that format (you can always strip them out later).We open the file like normal, and we create a list, which we have mastered by now. Then, we break the file into lines in our for loop using the in keyword. Python is magically smart enough to understand that it should break files into lines. Next, as we are looping through each line of the file we use myList.append(line) to add each line to our myList list. Finally, when we print it out, Python shows us its glory. It broke each line of the file into a string, which we can manipulate to do whatever we want.

Wait! Don’t forget to close the file!

Example
f = open("test.txt","r") #opens file with name of "test.txt"
print(f.read(1))
print(f.read())
f.close()

The important thing I saved until the end is that you should always close your files using the close() method. Python gets tired running around opening files and reading them, so give it a break and close the file to end the connection. It is always good practice to close files, your memory will thank you. Next, let’s do some construction by writing to files.