jump to navigation

Python for Newbies – Part1 January 26, 2011

Posted by rm42 in Computers, Python.
trackback

 

Table of Contents


What is Python?

Python is a computer programming language created initially by Guido Van Rossum, who released it to the world as an “Open Source” “Free”program. It has since then been progressively improved by the contributions of hundreds of computer programmers around the world. The Python package can be downloaded gratis from the internet for every major computing platform in existence. It can be used and even modified for just about any purpose.


Why Python?

There are many computer programming languages in existence. They all have different advantages and disadvantages. The brain of a computer is its processor. No processor understands English. The processor needs to receive input in a format that it understands. Most processors are made to understand commands formatted as a series of zeros “0” and ones “1”. This format is called binary. It is possible to write programs by hand using this format of zeros and ones, but it is very difficult, time consuming, and error prone. That is why computer programming languages have been invented.
Programming languages are frequently categorized as “low level” or “high level”. Low level languages were the first ones to appear. They simplified the process of writing instructions to the computer by allowing the use of normal words to be used in writing the program. A translator program, a “compiler”, translates the program’s instructions into a binary file that can then be understood by the processor. However, low level programming languages are still quite difficult to master. They force the programmer to understand the way the computer works internally. The programmer has to give instructions for every step that the computer must take to handle a certain task, which can easily lead to errors and serious problems. On the other hand, low level programs tend to be quite fast and efficient (if done correctly).
High level languages are designed to make it easier to program on. The instructions look more like normal language. And, a lot of the details are handled by the compiler. This makes for much shorter development time, but can also mean that the program is not as fast and efficient as a program would be if done in a lower level programming language.
Python is a very high level programming language. Many consider it the easiest programming language to learn and to program on. Many common tasks that would normally have to be programmed by the programmer are already built in to the language. Python is very useful as an easy and quick way to program anything from small little scripts to large scale client/server systems. This is especially true with today’s ultra fast computers that make up for the speed disadvantage inherent to high level programming languages. Programmers tend to like Python because of its clean and logical syntax, which shortens development cycles tremendously. It also forces programmers to use code indentation correctly. At first, some programmers see this as a challenge and unnecessary restriction. However, not long after beginning to use it, most programmers realize that it is easy to adjust to it and that it results in very clean code which is easily maintained (even if the code was written by someone else).


Installing Python

If you are using Linux, Python should already be installed, most likely with the right version for this tutorial. On Windows, just go to www.python.org/download/ and get yourself a download of Python 2.7, not the latest 3.x, since Python 3.x code is not compatible with this tutorial. (It is really not too different, but different enough to break things.) On Windows, I also recommend that you get the Windows extensions package, by Mark Hammond (get the latest build of the one that matches your version of Python). Other useful packages are the Python Image Library, and py2exe (for creating standalone Python executables).


How Python works

Python programs run with the aid of an “interpreter”. The interpreter is a program that converts the code into the binary instructions needed by the processor, at run time. There is an interpreter for each different platform where Python runs. This allows Python code written in a Windows machine, to run unchanged, in a Linux machine, a Macintosh machine, or even a smart phone. Of course, Python also has a lot of “platform specific” features that are optimized for the platform for which they are written. (Avoid these if you don’t want to tie your program down to a specific platform.) The interpreter must, either be installed on the computer that needs to run the Python program, or the Python program must be packaged in conjunction with the interpreter so that it can be run by computers without Python.

The interpreter can be run directly in what is called the “Interactive Command Line”. Python commands can be typed directly into this session and they are processed immediately showing the results of the command. This unique feature allows for quick and easy testing of ideas and code.

Most Python programs, however, are written with some type of text editor, saved as plain text files with a .py extension, and run as an independent process. Since there is no need to “compile” a Python program before running it, a programmer can test its changes to the code immediately after saving them.


The building blocks of a Python program

First of all, what is a “program”? Well, at its most simplest form, a program can be defined as one or more instructions given to a computer for processing. Normally, those instructions are saved or recorded in some way before passing them on to the computer. In Python, however, as we said above, we can also hand those instruction to the computer directly, interactively.

Lets enter Python’s interactive mode by opening the Terminal application (or Command Prompt) and enter the following command:

python

Now, let’s do our first program as it is traditionally done:

>>> print "Hello World"
Hello World

Here, the word print is a built in command or “statement” that sends the given argument to the screen. The second part of the program, what follows the print statement, is the argument itself, in this case, the string "Hello World". The quote marks tell Python to treat the words inside of them as a string, rather than as a command or a variable. (A “string” is a sequence of characters, like a word, a sentence, etc. They are further explained latter in this section.)

Note:
Typically, in Python manuals and tutorials, when showing python code entered in an interactive session the >>> represents the Python Command Line prompt. When a compound statement is being defined (one that takes more than one line), Python switches to … as a prompt.

Note:
Text typed after a # is referred to as a comment, and is ignored by the Python interpreter.


Variables

What is a variable? Put simply, you can think of a variable as a name (a word) that refers to a certain value. We can use almost any word and assign a value to it. For example:

>>> hi = "Hello World"

The word hi is now the name of a variable who’s value is the string "Hello World". Let’s use the print statement to send the value of hi to the screen:

>>> print hi
Hello World

In Python, variables are very flexible. You don’t have to declare them first, like in other languages. You can assign any value to them, even if they already have a value of a different type. For example, let’s change the value of hi to 3.0:

>>> hi = 3.0
>>> print hi
3.0

We can also assign a variable as the value of a variable. For example:

>>> num = hi
>>> print num
3.0

Another neat feature of Python’s interactive shell is that you don’t even have to use the print statement to see the values of variables and other objects. You can simply type their name and Python will display it.

>>> num
3.0


Expressions

At the interactive command prompt one can type expressions and see their result interactively. “An expression is a combination of variables, operators and values that represents a single result value”*. For example:

>>> num + 2
5.0
>>> ((5 – 1) + num) * 2
14.0

We can assign the value of an expression to a variable. Such as:

>>> numb = ((5 – 1) + num) * 2
>>> numb
14.0


Numbers

Notice on this last example that the number returned by Python is a number with a decimal point. In computer terminology this is called a floating point number. Since the expression included a floating point number (3.0), the expression’s value was automatically converted into a floating point number. The reason for the distinction in number types is beyond the scope of this tutorial. In most computer programming languages, one has to be careful to use the right type of number for each application. In Python, it is good to know that there are different types of numbers, but Python will usually deal with the details quite well. The only caveat to currently watch out for is division. Notice this:

>>> 7 / 2
3

Since both numbers in the division are integers (a type of number without decimal places) Python performs an integer division. This may not be what someone new to programming expects. Currently, to work around this one can do things like this:

>>> 7.0 / 2     # or float(7) / 2
3.5

In more recent versions of Python (version 3.x), Python’s designers have decided to change the way this works so that it does what new users would expect. With the 2.7 version of Python one can already import this behavior from the “__future__” module. We will see more about ‘importing’ latter.

Some common operators associated with numbers are:

Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder (e.g. 9%2=1; 8%2=0)
** Power (4**2=16)

There are also many math functions in Python for doing just about any operation needed. Here is a small sample (see the documentation for more). To access them you need to first import them from the math module, like this for example:

from math import acos

Function Description
acos(x) Return the arc cosine of x
cos(x) Return the cosine of x
log(x) Return the natural logarithm of x
sqrt(x) Return the square root of x
tanh(x) Return the hyperbolic tangent of x

A handy tip is that in the Interactive Command Prompt you can recall the last printed expression with the underscore character “_”. So for example, you can use Python as a handy calculator this way:

>>> 2 + 2
4
>>> _ + 6
10

There is also a special Python extension called Numerical Python (NumPy) which allows it to become a tool for higher math functions such as linear algebra and matrices. But, enough of numbers for now.


Strings

We already saw an example of a string in the “Hello World” example. “A string is an ordered collection of characters, used to store and represent text-based information”. Python strings can be enclosed in double, single, or even triple (for multi-line strings) quotes. For example:

>>> 'Hello World'
'Hello World'
>>> "Hello 'Hello World'"
"Hello 'Hello World'"
>>> '''This is a longer string that spans
… several lines, doesn’t say anything
… meaningful, and ends here'''

The fact that strings are “ordered” means that we can access their components by position. Each character in a string has an index position before it. For example the string “Python” has the following indexes:

String Indexes

Notice that the first character “P” is located at index 0, as in programming languages like C, not 1 as in languages like Basic. However, unlike C, with Python you can also use negative indexes, which start counting from the end of the string.
To get the characters located at certain indexes we can use their index number inside brackets. Let’s look at some examples.
To get the character located at the beginning of the string we can use:

>>> "Python"[0]
'P'

Or if we are using a variable:

>>> hw = "Hello World"
>>> hw[0]
'H'
>>> hw[1]
'e'
>>> hw[-1]
'd'

We can also get “slices” of a string by specifying the first and last index of the slice separated by a colon.

>>> hw[1:7]
'ello W'
>>> hw[4:-2]
‘o Wor’

The left or right bounds of the string can be specified in a slice by leaving the index blank. For example:

>>> hw[:5]
'Hello'
>>> hw[6:]
'World'
>>> hw[:]
'Hello World'

Strings are very smart “objects”. They know how to behave correctly in many situations such as:
When adding a string to a string:

>>> hw + " Today"
'Hello World Today'
>>> hw[:5] + " You"
'Hello You'

Multiplication:

>>> hw[:6] * 5
'Hello Hello Hello Hello Hello '

Notice that in all the operations we have done so far with strings, the operation returns a result but the original string remains unchanged. That is how strings work. A string is what is called an “immutable sequence”. What this means is that to change a string we actually have to create a new string. For example:
Trying to change the value of a string character in place

>>> hw[0] = "M"

This raises an error!

However, since variables are so flexible we can simply assign a new value to it:

>>> hw= "M" + hw[1:]
>>> hw
'Mello World'

This works because the hw[1:] expression is calculated first, then "M" is added to it, and finally the result is assigned as the value of the variable hw.
Another way to join strings with variables is by means of string formatting. For example, what if you had a program that greets the user by name according to the time of day. For example, it could say something like: “Hi Joe. How are you this morning?”. In this case the program could gather the name of the user somehow and place it in a variable called “name”. It could also fetch the time of the day by looking at the computers clock, determine if it is morning, afternoon, or evening, and place the result in a variable called “time_of_day”. You could then have the following line in your program to merge them into a string:

>>> Greeting = "Hi %s. How are you this %s" % (name, time_of_day)

Python replaces the occurrences %s with the respective variable in the tuple after the % character. (A “tuple” is a sequence of items inside a parentheses. Tuples are further explained latter in this tutorial.) Here is another example:

>>> dessert = "Pecan Pie"
>>> max_per_person = 1
>>> answer = "The dessert of the day is %s. You can only take %i per person" % (dessert, max_per_person)
>>> answer
"The dessert of the day is Pecan Pie. You can only take 1 per person"

In this example we added a string variable and an integer variable into the answer string. Strings and integers have different formatting codes (%s, %i). See Python’s documentation for other formatting codes.

Strings also have built-in methods such as the following:

>>> "hello".capitalize()
'Hello'
>>> "HELLO".lower()
'hello'
>>> 'hello'.upper()
'HELLO'
>>> 'Hello World'.replace(" ", "-")         #Replace occurrences of first parameter with second
'Hello-World'
>>> ' Hello World '.lstrip()         #To strip the whitespace at the left of string
'Hello World '
>>> ' Hello World '.rstrip()         #To strip the whitespace at the right of string
' Hello World'
>>> ' Hello World '.strip()         #To strip the whitespace at the left and right
'Hello World'
>>> "This is a longer string".split()
['This', 'is', 'a', 'longer', 'string']

On the last example we see how the split method returns a list of strings. It separates the original string by some given delimiter. When none is given, the default, whitespace, is used. But, what is a list?


Lists

Like strings, lists are ordered sequences. So, they share many of the same functionality. However, lists are mutable sequences, that is we can change them in place. Also, unlike strings, lists can contain any type of object: numbers, strings, even other lists. Much of the simplicity, power, and popularity of Python comes from this built in object type.

To define a list, we simply have to enclose it in square brackets using commas as item delimiters:

>>> L = [1, 2,'three', 4]

The L variable is now a list object. We can use indexes and slices to access its members:

>>> L[0]
'1'
>>> L[2:]
['three', 4]

And, as mentioned before, we can change them in place:

>>> L[2] = 3
>>> L
[1, 2, 3, 4]
>>> L[0] = ['one', 'two', 'three']
>>> L
[['one', 'two', 'three'], 2, 3, 4]

We can also concatenate lists (add them together):

>>> L + [8, 9]
[['one', 'two', 'three'], 2, 3, 4, 8, 9]

And repeat or multiply:

>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]

We can delete items from lists using the del function:

>>> L = [['one', 'two', 'three'], 2, 3, 4]
del L[1]
L
[['one', 'two', 'three'], 3, 4]

Or even:

del L[0][1]         #Deletes item at index 1 of L[0]
L
[['one', 'three'], 3, 4]

Lists can be sorted and reverse sorted:

>>> L = ['c', 'b', 'a', 1]
>>> L.sort()
>>> L
[1, 'a', 'b', 'c']
>>> L.reverse()
>>> L
['c', 'b', 'a', 1]

Notice that the sort and reverse methods do not return a new sorted list as a result. They simply change the list in place and return a special value called None. To see the results of the sort we have to print the list.

Another little peculiarity to watch out for when using lists is the following:

>>> L1 = [1, 2, 3]
>>> L2 = L1
>>> L2
[1, 2, 3]
>>> L2[0] = 8
>>> L2
[8, 2, 3]
>>> L1
[8, 2, 3]

Notice that changing an item in L2 also changed it in L1. The reason for this is that when we assign L1 as the value of L2 what Python actually does is assign a pointer to L1 as the value of L2. In other words, they are linked. If this is not the desired result, you can avoid it by doing the following:

L2 = L1[:]

Because slices return new lists, assigning a slice of all the items of L1 as the value of L2 results in L2 being a new, independent list, a clone of L1.

So as you can see lists are very easy and friendly to use. In Python lists have a very close relative. Let’s take a look at it now.


Tuples

Tuples are very similar to lists. The difference (and the reason for their existence) is that tuples are immutable. In other words, they can not be changed in place. Other than that everything we saw about lists also applies to tuples.

Tuples are defined by parentheses:

>>> t = (1, 2, 3)
>>> t[1]
2
>>> t[1:]
(2, 3)

Earlier we saw that strings know how to convert themselves to lists using their ’split’ method. We can also convert a string into a tuple with a function called tuple. It works like this:

>>> tuple('some string')
('s', 'o', 'm', 'e', ' ', 's', 't', 'r', 'i', 'n', 'g')

You may wonder when will you ever use tuples, since lists do everything tuples can do and more. Well, among other reasons, since tuples are immutable, they are handy whenever you want to make sure that they do not accidentally get changed by some call. Some built in operations require tuples. And last but not least, tuples make for excellent dictionary keys.


Dictionaries

Dictionaries allow us to collect all kinds of objects just as lists and tuples do. However, rather than fetching them back through the use of index or offset location, dictionaries allow us to fetch their items by keys. So, for each item in a dictionary, there is an accompanying key. Here is a dictionary example:

>>> d = {'key1': 'dog', 2: 'cat', ('key', 'number', 'three'): 'mouse'}

As you can see, dictionaries are enclosed in curly brackets ‘{}’, and each key-value pair is separated by a colon ‘:’. Notice that we can use strings (‘key1′), numbers (2), and tuples ((‘key’, ‘number’, ‘three’)) as dictionary keys. All of these are immutable type objects. Values can be anything we want: strings, lists, …, and even other dictionaries, which contain other dictionaries, that contain other…. Like lists, dictionaries can be modified in place. However, they are not ordered sequences so, as we said before, we can not use indexes or slices to retrieve their items. It is important to remember that the order in which dictionary items appear is not to be relied upon. Nevertheless, Python offers very simple ways to work with dictionaries. Let’s look at some examples.

Retrieving a value:

>>> d['key1']
'dog'
>>> d[2]
'cat'

Changing the value of a key:

>>> d['key1'] = ['milk', 'cake']
>>> d
{('key', 'number', 'three'): 'mouse', 2: 'cat', 'key1': ['milk', 'cake']}

Notice that on the last example the order of the dictionary items is printed differently than how we entered it. Now let’s add a new entry:

>>> d['new'] = 1.5
>>> d
{('key', 'number', 'three'): 'mouse', 2: 'cat', 'key1': ['milk', 'cake'], 'new': 1.5}

As with lists, to delete an item we can use the del function:

>>> del(d[('key', 'number', 'three')])
>>> d
{2: 'cat', 'key1': ['milk', 'cake'], 'new': 1.5}

Two very important operations that are frequently needed is the ability to retrieve all the keys or all the values contained in a dictionary. Python does this easily:

>>> d.keys()
[2, 'key1', 'new']
>>> d.values()
['cat', ['milk', 'cake'], 1.5]

Notice that in both instances Python returns a list of the items we requested. This is handy because we can then use any of the functions and methods associated with lists, such as sort and reverse, to arrange them in the order that we want. We could then iterate through each item in the right order, in spite of the fact that dictionaries are unordered collections. You may now wonder, what is to iterate? This brings us to our next major subject.


How to program in Python

In this section we are going to see how we can use the different data and object types that we have already covered, as well as a few others, to put together full scale programs.
Up to now all we have done is review some of the main object types available in Python using quick little one line expressions that do a single operation. However, the real power of computer programming is its ability to have the computer do multiple things for us with one simple command on our part. The concept of iteration is a good example of this.
Iteration is “the process of repeating a set of instructions a specified number of times or until a specific result is achieved”*. For example if we had a list with five items and we wanted to print each one of them, we could manually type five lines of code that would print each item. But what if we did not know how many items the list contained at any particular time, or what if the list contained hundreds of items? Well, actually the solution is very simple. This is how we would do it in Python:


“for” Loops

As we have seen already, lists can be of any length we desire. Lets see what we can do with a little list of 5 items.

>>> L = [1, 2, 3, 4, 5]
>>> for i in L:
…     print i
1
2
3
4
5

What we are doing is iterating through the list L, assigning a temporary variable named i (can be whatever you want) for each item in L, and printing it. Here is another example:

>>> students = ['John', 'Peter', 'Jeremy', 'Carly']
>>> for student in students:
…     print "You are a very good student, %s. " %(student)

You are a very good student, John.
You are a very good student, Peter.
You are a very good student, Jeremy.
You are a very good student, Carly.

This construct is called a for loop. It is the first compound statement that we look at. Notice that the first line, the header, of the loop terminates in a colon. Notice also that the second line of each of the two examples above, are indented. This is very important, as we will see later. The body of a for loop doesn’t have to be limited to one line. It can contain as many lines of commands as desired. It will execute all the commands of the body for each iteration, unless otherwise told in the code.
It is important to understand that the for loop is a sequence iterator. It can iterate through ordered sequence items, such as strings, lists, tuples, etc. This will carry you a long way in your programming needs. However, there is another way to iterate or repeat a series of commands. But before we see it, you need to understand another important concept.


“truth” Tests

In computer programming, certain expressions evaluate, to either truth or false. For example, we know that it is true that 5 is greater than 4. Python knows that too, and this is how Python expresses that:

>>> 5 > 4
1

As you can see, the expression 5 > 4 returned a value of 1. In programming, when evaluating the truthfulness of an expression, 1 is the common value for true and 0 is the common value for false. For example:

>>> 4 == 5
0

On this example you can see that to evaluate the equality of two values we used two equal signs rather than one. This is because, as we saw earlier, one equal sign is the assignment operator. So remember to use two equal signs when evaluating equality.
Besides math operations, Python recognizes other expressions as either true or false. For example, empty data types, like an empty string, list, etc, evaluate to false. There are also many operators that can be used inside a truth test expression. See the Python documentation for these if you are interested.
You will understand truth tests better by seeing them in action. So, let’s dive into our second method of iteration.


“while” Loops

A while loop repeats a set of commands until some terminating condition is met. They may never execute the body of the loop if the terminating condition is false to start with. Here is a basic example:

>>> x = 1
>>> while x < 10:
…     print x,
…     x = x + 1
1 2 3 4 5 6 7 8 9

Here you can see that the condition that we test for is whether x is less than 10. This little loop will continue repeating itself until that condition is false. You may also notice that by adding a comma at the end of a print statement it does not print a new line character after each print. So, all the numbers are printed in the same line.
One important lesson to remember with while loops is that, unless you want the loop to run forever, you should be sure that the condition will eventually be false. Let’s just look at another simple example to solidify your understanding:

>>> s = 'Something'
>>> while s:
…     print s,
…     s = s[1:]     # Removes the first character of the string
'Something' 'omething' 'mething' 'ething' 'thing' 'hing', 'ing', 'ng', 'g'

In this case, once the string is empty, the while loop stops because s evaluates to false.
So, as we can see, without truth tests while loops would not be possible. However, there is an even more basic programming feature where truth tests play a key role. With it we will be able to start adding real intelligence to our programs.


“if” Statements

The if statement allows our programs to select a course of action depending on whether or not a certain condition exists. The if statement is the third multi-line or compound statement that we look at. Let’s look at an example:

>>> if 5 > 4:
…     print "Life is good"

As in the previous compound statements, if statements have a header. The header begins with the if word itself followed by the expression that is to be evaluated, and ends with a colon. Again the body of the statement is indented.
Let’s look at a more realistic example:

>>> first_name = 'Bob'
>>> last_name = ''
>>> Greeting = 'Hello %s %s' % (first_name, last_name)
>>> if first_name and last_name:
…     print Greeting

In this example we can see that the Greeting would only be printed if both first_name and last_name evaluate to true. Since, in this case, last_name is an empty string it will evaluate to false, and the Greeting will not be printed. Python will simply continue to its next command outside of the body of the if statement. Let’s look at another example:

age = int(raw_input("How old are you? "))     #The int function returns its input as integer.
gender = raw_input("Are you male or female? ")
if age >= 13 and age <= 19:
    if gender.capitalize() == "Male":
        print "You are a teenage boy."
    else:
        print "You are a teenage girl."

The raw_input function allows us to get input from the user. If we type those commands in a file named test.py and ran it as a script from the Command Prompt (e.g.: ~\somedirectory>python test.py) we would get the following output:

How old are you? 15
Are you male or female? Male
You are a teenage boy.

Here we can see that “if” statements can be nested inside other “if” statements. The same is true for any other compound statement. You can nest compound statements as deep as you like. In this example we also see that an “else” statement can be used in conjunction with an “if” statement. An “if/else” combination allows the program to decide between two courses of action. Only one of the two will be executed. A similar construct is the “elif” statement (which stands for “else if”) which allows the program to choose from any number of ways to proceed depending on which condition is found to match first. For example:

>>> if day == "Saturday":
…     print "Happy day"
… elif day == "Sunday":
…     print "Weekend is almost over."
… elif month != "August":
…     print "Today is not an August weekend"
… elif hour > 22:
…     print "Time to go to bed"
… else:
…     print "Today is not a weekend, it is August and I still have time to do something"

With “if” statements we can give our programs many options to select from. It will check each one in order and select the first one that returns a true evaluation. Notice that the “not equal” operator (!=) returns a true evaluation if the “Month” variable is anything other than “August”. Something to watch out for in this kind of construct is that the “Time to go to bed” string will not get printed even if it is past 10:00 p.m., unless all the previous options were false. And finally, notice that we ended the sequence of statements with an else block. This one will get executed for sure once all the previous options proved false.
So, as you can see, truth tests in conjunction with if/elif/else statements can be very powerful in helping you express the logic of your program. The if statement is very often found inside while and for loops to change the flow of operation of the loop or to exit the loop if a certain condition is found. Let’s look at an example:

>>> L = ["mouse","", "cat", "dog", "parrot"]
>>> for animal in L:
…     if animal == "dog":
…         print "Dogs are not allowed"
…         break
…     elif animal == "":
…         pass
…     else:
…         print "What a nice %s you have" %(animal)

What a nice mouse you have
What a nice cat you have
Dogs are not allowed

The break statement is used to exit the current loop. If the loop of this example had been inside another loop, the break statement would have simply continued to the next iteration of the outer loop. The pass keyword simply tells Python to do nothing. Again, notice the all important use of indentation to correctly identify the end of nested statements.
What we have covered so far is enough for you to be able to write very rich and powerful programs. However, we have just touched the most basic elements of computer programming. There are a few more concepts to learn in order to take full advantage of what can be done in Python. We will look at them in Python for Newbies – Part 2.


About this tutorial


I learned Python from a few different sources. I picked up quite a bit from several online books and tutorials, such as this one. However, neither of the online tutorials felt easy enough for me. Most of them felt like they were made by geniuses for geniuses. I wanted something that expressed the concepts more simply and more logically, without making me do intellectual gymnastics to get there. Fortunately, I found that the book Learning Python, by Mark Lutz, was exactly what I was looking for, and finally got me over the learning hump.

I first created this tutorial in 2001 while volunteering at a non-profit organization. It was originally meant to encourage the use of Python within that organization. I tried to condense the ideas and the logic found in the “Learning Python” book and make them even more simple. The book Learning Python is a lot more comprehensive and I definitely recommend it to any one seriously interested in getting into Python. This tutorial is good for those that want to ease into Python or into programing in general.

The version of Python and other libraries targeted by the tutorial will be initially 2.7. Python 3.0 has several changes in the language that make it incompatible with this tutorial. I hope to incorporate those changes into this tutorial some time in the future. Some sections of this tutorial, specifically the GUI portions, have not yet been finished.

This tutorial is made available to you under the Creative Commons Attribution-Share Alike 3.0 license:

http://creativecommons.org/licenses/by-sa/3.0/
http://creativecommons.org/licenses/by-sa/3.0/legalcode

Joe Crawford has been working on an expanded version of this tutorial. I haven’t had a chance to review it, but you may want to take a look at it. It can be found here:

http://www.teaching3d.com/w/?page_id=188

Comments»

1. andy - January 27, 2011

A super, easy-to-understand introduction to python and programming concepts in general which we will be recommending to students we know, even though they won’t be learning python first. Thanks for taking the time to write and share this.
Andy
P.S. The link for downloading python is broken – it has your own address prepended to the real one.

rm42 - January 27, 2011

I’m glad you like it. And thanks for the heads-up about the link.

2. Chad McCullough - January 27, 2011

Wonderful! I’m a Perl programmer that has been wanting to learn more about Python for quite some time. This is very helpful.

3. Kurt Vanderwater - January 27, 2011

Nice and concise… A good quick review.

Interesting that I found this today and you mention the GUI…. I am currently looking for some information on how to do Drag&Drop Widget layout and then have the code generated. Kinda like the old Visual-Age products used to do.

rm42 - January 27, 2011

I recommend that you look into PyQt.

PraveenMax - February 2, 2011

wat about wxPython?wxPython is more open than PyQt and it still has most of the features.

rm42 - February 2, 2011

Yes, wxPython is cool. I have actually used it in the past for some small apps. I should probably include a section for that. But, what do you mean when you say it is more open? PyQt is GPL (although you can probably get a different license if you contact Riverbank). And, the Nokia sponsored version being developed,PySide, is LGPL.

The problem with wxPython is that it is a lot more verbose, and feels a lot less ‘pythonic’. And there is nothing comparable to QtDesigner for wxPython, at least that I have seen.

4. patrick silwimba - January 28, 2011

Thank you very much for this tutorial.

5. Howard Pepper - January 28, 2011

Nice, simple tutorial. I posted a link to this site on my LUG Yahoo group.

6. mohammad - February 9, 2011

Thank you, this is exactly what I have been looking for

really thank you !


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: