free hosting   image hosting   hosting reseller   online album   e-shop   famous people 
Free Website Templates
Free Installer

Python programming for complete beginners

Intended Audience:

Table Of Contents

    Preface

  1. The Bare Basics

  2. Data Types

  3. A Brief Introduction to Compound Statements

  4. Control Structures (if... else for while)

  5. Functions

  6. Modules

  7. An introduction to Classes and Object Oriented Programming


Preface

I. What is Python?

Python is in essence, a simple object oriented scripting language with many built in mechanisms. Some of python's features are:

Python is an interpreted language, which means, it reads plain text files and then executes the necessary commands on on the Operating System which then intern accesses CPU and Memory. This is one of the reasons why Python is a Very High Level language, it also has it's own memory management system.

Python files:

myProgram.py - Source code(program code file)
myProgram.pyc - Byte code compiled source file(this source file is neither plain text nor machine code, and is optimized to be read by the Python interpreter)
something.pyo - Python Byte code compiled library(I'm not 100% positive on this one though)

II. Why learn Python?

Python is extremely easy to learn, it's a whole lot of fun. Python is also a high productivity programming language, because you can learn new things so quickly. Python is less autocratic and restrictive than other programming languages, expecting the programmer to be friendly toward his interface, rather than the other way around. Python does not replace any other language, and fills a unique void in the programming world. Python is also a great first programming language to learn, because the first one you learn will always be the one you fall back on if anything goes wrong, and having Python under your pillow is great.

III. Is python similar to Java?

In some respects it is, Python is similar to java in the sense that both are multi platform, and both can compile their programs into intermediate versions. Syntactically speaking though, python is not very simi liar to any programming language, and the reasons for this only become obvious when you know the language a bit better. Unlike Java, Python did not borrow heavily from C syntax.

IV. A brief description of this tutorial

In this tutorial I will try to highlight some important aspects of programming, and attempt to illustrate some mistakes that beginners make, and that some experienced programmers even make. This tutorial is mostly for beginners of programming, but if you have experience with other languages you may also use this tutorial. Large parts of this tutorial is code, and I attempt to illustrate with code as far as possible. In this tutorial I attempt not to use "future knowledge" in any programs, which means that each program is explained fully and does not assume any previous knowledge. It is assumed that throughout this tutorial you will be pasting examples, experimenting with them, and trying to write your own.

One of the greatest misunderstandings in programming history is probably that you can learn a programming language by reading it. If you do this, you might understand everything, until you close this window and try to do it yourself. Try to ease yourself into the knowledge given here. As a last note, try not to do this all in one hour or even a day. Take bites that you can chew, and more importantly, swallow.

V. Getting Python

The first thing you need to do is to get python at

www.python.org

Also download the documentation as this is an essential part of the Python package!

Install this package and reboot if necessary. Now find python in your program menu(windows) and click on IDLE.
This program has a prompt, but we're not interested in that right now, so click on file, click new, a blank window pops up. now grab some coffee and get ready to learn python.

Back to top


1. The bare Basics

1.1 Your first program

Because I don't believe in delay, we will start by writing a program. Don't panic, it's very easy!

Now put the following code into the blank document window in IDLE(including the lines that start with #), save the file as lesson1.py

#beginning of code
print "We are the knights of ni!"
print 5 + 3
#end of code

now press F5( this will automatically run your program). The output should be:

"We are the knights of ni"
8

Analysis:

The first and last line are comments, which are explained next.The print statement in the second line is used to print things to the screen, also notice that the text is enclosed in double quotes, we must put strings(text) in double quotes so that the interpreter knows what it's reading and when to stop.
In the 3'rd line we print 5 + 3, and the number 8 is printed on the screen, this is because Python evaluates(computes) the resulting value of the expression.

Terminology: "print 5 + 3" is an example of a statement. A statement is a single entity of execution.

1.2 Comments

The first and last line have no effect on the program, that means, that if we leave them out the program will be unaffected. the interpreter intentionally ignores any text after a # sign, unless the # sign is enclosed in double quotes. The reason for this ignorance is that you(the programmer) can say things about the code you are writing, for instance:

# This is my second program, that illustrates comments
print "#this is not a comment" #this is a comment, and the interpreter ignores it
#comments can only be on one line, so if you want a second line in your comment, simply do
#This :)

1.3 Storing data

Often it is necessary to store a value so we can retrieve it later. In order to do this we need to declare a variable, which is a storage area in memory. The following program illustrates how we can store and retrieve data:

#beginning of code
myVariable = 15
myName = "Lancelot"
print myVariable
print myName
#end of code

Analysis:

Some very important concepts come through in this small piece of code. One of those concepts is data types. Note that I can store both numbers and text without specifying what type of data it is. This might seem silly now, but most programming languages require you to specify the specific type of data you will be storing in a variable. Python figures it out for you in some cases, but later you will notice that you need to convert certain variables before you can perform certain operations on them.

Another important concept here is naming of variables. Notice that instead of typing myvariable = 15 i typed myVariable. This makes the variable name more readable, to illustrate this concept more fully consider the following 2 variables

gasstationname
gasStationName

The second variable is easier to read, there are many different ways of naming variables, no matter which one you choose, remember to minimize key strokes and at the same time keep the variable as descriptive as possible.

Note: Python is case sensitive. print and Print are not the same thing, and this extends to every keyword and variable name in python

 

1.4 User input

A program would have no use if it didn't receive input or of some sort. Programs are made to interact with people and often you need people to give you data. The following program will take in someone's age and print out their year of birth.

# filename: age.py
# Author: Tjaart Blignaut
# Description: Calculates your birth year from your age

age = raw_input("How old do you turn this year: ") # This statement reads input from the keyboard
birthYear = 2006 - int(age)
print "You were born in the year " + str(birthYear)
# EOF

Analysis:

In the first three lines I have expanded comments to include some information about the program, this is good practice, you can also include your e-mail or ICQ number in there if you want to get feedback about your code. You may want to include a license to specify how the code should be used or a copyright notice(note that all code you write is automatically copyrighted to you).

In the fourth line I have used the raw_input() function to put the value from the keyboard into the variable age, also notice that the question is very specific, instead of "age?" or "how old?" try to give the user a clear understanding of what you want.

In the 5th line you will notice something new.The int() function. This function is used to tell the interpreter that the text entered by the user is a number, we do this so that we can perform calculations on it. Note that the age variable is still a string(text) and the int function only converts the value of age temporarily so that the calculation can be performed on it. The answer to the calculation is now stored in birthYear, which is an Integer.

In the 6'th line, we are printing the result, note that once again we must perform a conversion, this time using the str() function. This is so that we can concatenate(add) the birthYear variable to the "You were born in the year " string. If this function is left out the interpreter will generate an error, because it can only add two strings together in this context. Don't understand? To put it more simply you cannot add text to a number, because they are different types of data.

On the last line I added a comment that just explains that that is the End Of File, if someone was working with only half of the program code they wouldn't know why it isn't functioning, this # EOF comment just clarifies that it is the end of the file and that no more code is to follow.

Python will determine the type of a variable based on what you put into that variable.

Back to top


2. Data types

2.1 Numbers And Arithmetic


In python declaring an integer is as easy as this:

myInt = 5
yourInt = 10

The above code declares two integers named myInt and yourInt in memory. And now we may use them to do some calculations. The code continues here:

anotherInt = myInt + yourInt

anotherInt is automatically created by the interpereter and the values of myInt and yourInt are added and put into it. When we are programming though, things get a little tricky from here on out, because things don't always work as you expect them to. Consider the following:

print myInt / yourInt

In mathematics the answer is 0.5 right? Not in programming. This program will output zero. This is not a mistake. Later on you will realize why this is a better way for programs to work. But now your asking how do i get 0.5 as an answer then. It's quite simple really:

myInt = 5.0
print myInt / yourInt

Now the 0.5 is printed to the screen. Which is what youd want it to do. When we added the .0 to the end of myInt it became a floating point number. With floating point division you will get mathematically accurate answers. With integers however, you will always get an integer as an answer. As soon as you divide by a float the interpreter will automatically convert the numbers and you will get a floating point number as an answer.

2.2.1 Some arithmetic

The following are valid arithmetic operators in python:

Operator Function Example Result
+ Adds numbers on both sides 5 + 8 13
- Subtracts numbers 10 - 5 5
/ Divides numbers 15 / 3 5
* Multiplication 5 * 4 20
% modulus 8 % 3 2
** Powers 2**3 8

In the examples above I illustrated each of the operators with an example. If your still shaky on what modulus is, I will atempt to explain it quickly. Know these operators!!! They are very important.

2.2.2 Modulus

First of all, modulus is not the devil. It seems a litle strange at first, but it has some really cool applications. Modulus does integer division, like I explained before. With integer division 7 / 3 is 2, and the remainder is discarded. Modulus gives you this remainder. With this in mind remember that you cannot perform modulus on floating point numbers because whn you divide floating point numbers you don't ever have a remainder. Ever! Here is a an example of a common use of modulus. When the year is devided by four, and there is no remainder, it means it is a leap year.

print thisYear % 4

2.2.3 Order of precedence

In math we learn that when an equation is done, we start with powers, then we do multiplication and division, and then we do addition and subtraction. Python is no different to math in this aspect, and you may also use brackets to clarify your equations and order of processing. This is very important. The following python statement is valid:

print (4**3 * 12) / (2**3 + (12 * 6))

As you may expect, the inner most brackets are evalauated first. I'm not going to expand too much on order of precedence, as the Python tutorial already explains it, and math does too.

 

2.2 Strings

2.2.1 What's a string?

A string is an arbitrary list of characters. A string can be anything you want it to be, here are some strings printed to output

print 'Sketch: The philosophers song'
print "This string will print\nOn two lines"
print "The date is 12/12/06"
print """ This string will be printed exactly the way
It looks like here , with the new lines included
don't forget the \"\"\" with this one"""
print 20 * "*"
print "This is how you show a single backslash : \\"
print "This is how you make a single quoted string \
Span \
Multiple lines in your code"

In this example I have shown some aspects of strings in Python. Firstly and very importantly a string always starts with a " or a ' or a """, and always ends with a termination of the same type. The \n in the second print statement is used to go to a new line.Note that if you want to have a \ in your string and display it, you must use \\ as shown in the last example.

Important Note: An un terminated string is an error, and a single quoted string must be terminated before the end of the line, to make a single quoted string span multiple lines you can do this:

2.2.2 Basic string Processing

So now that you can make strings, you'd like to mix it up a little, throw in some variables, do some calculations, maybe you want to find out how many times a swear word is used in a line of text. Lets do that:

swearword = "fudgepickle"
swearline = "I don't give a fudgepickle about programming, because this fudgepickle of a program wont work, and I'm going to break out in fudgepickles now"
print "The word " + swearword + " was used " + int(swearline.count(swearword)) + " times in the sentence: \n" + swearline

2.2.3 String slicing

String slicing is a very simple, but very useful python feature that allows you to do some amazing things with strings. There is not much to explain, so I will simply show some examples here:

aVariable = "the quick brown fox jumps over the lazy dog"
print aVariable[:3] # only from the third character onward
print aVariable[4:9] # from character 4 to character 9
print aVariable[3:-3] # from character 3, up to the 3rd last character
print aVariable[:-3] # everything except the last three characters
print aVariable[-3:] # Just the last three characters

There is one thing to remember here, you cannot use assignment with slices, because strings are immutable, meaning individual elements cannot be changed. The following is therefore invalid :

myVariable[4] = "k"

2.3 Lists

Lists are practically self explanatory. A list is a data type that holds many values, So without delay, here are some of the ways we can make our own lists

pets = ["dog","cat","parrot","goldfish","hamster"]
print pets[0]
# EOF

To add an element to the end of a list:

pets.append("Shark")

To remove an element from the list

pets.remove("goldfish")

To count the amount of elements in the list

print len(pets)

Program output :

dog

2.3.1 Nesting Lists

A list can be nested. This means that we can put one list in another one, for as many times as you like, for instance:

names=[["Tjaart","Blignaut"],["John","Smith"],["Sir","Lancelot"]]
print names[1][0]

This will print "John" to the screen. Why? the list is referenced from zero, so the second element in the top list is ["John","Smith"] by index. Element zero is "John", in the nested list. Get it? If you don't, try changing the indexes and see the output you get. Note that an invalid index will generate an interpreter error: "Index Error: list index out of range". This simply means you tried to list an element that doesn't exist.

2.4 Tuples

Tuples are much like lists, but they are what we call immutable, whilst dictionaries are mutable. Tuples don't support index assignment. That is you cant say myTuple[2]. this is invalid, and example of creating a tuple would be:

myTuple = (5,"wippee",34,21)
print myTuple[1]

This will print "wippee" to the screen. Tuples are useful for storing tings like x,y coordinates, names and surnames etc. As a guideline NEVER USE A LIST WHERE YOU SHOULD USE A TUPLE, as I did in the previous example with names and surnames, unless you want to change the contents of individual elements. Rather do this:

names=[("Tjaart","Blignaut"),("John","Smith"),("Sir","Lancelot")]
print names[1][0]

This will create a list with tuples of names and surnames inside.

2.5 Dictionaries

A dictionary is best explained as an associative array. Dictionaries can store a values, matched by keys. Here is an example:

myDict = { "name" : "Tjaart" , "Number" : 555333 }
print myDict["name"]

This small segment will print "Tjaart" to the screen. Dictionaries can also be nested, and can be very cool if your working with data that you don't want to index by number, as is with lists. An example is a dictionary that holds host names and their associated connections, but that could be a topic of an entirely different tutorial :)

Back to top


3 A Brief introduction to compound statements

3.1. Introduction

Before I wrote this chapter, I had written the chapters that follow after it. I realized that there was a great piece of missing knowledge to be desired from the previous chapters. So here it is

3.2 What are compound statements

A compound statement is any statement that can be elaborated into more statements. Each of the statements belonging to the parent statement is indicated by indenting these statements and each compunt statement is ended with the indentation level returning to where it was before. Compound statements are always followed by a colon. This is how Python syntax works. Here is an example of an if statement

if cheese == "Limburger":
         print "It's runny sir, very runny"
print "not in compound statement anymore, because indentation level returned"

As you can see the preceding example, the print statement on the second line is indented, and therefore belongs to the if statement.

3.3 Compound statements can be nested

In Python, most compound statements can be nested. It is more typical to nest some than others.

3.4 Scope

In some compound statements variables declared inside them will be unique to them, and will be destroyed as soon as the compound statement ends, or when the object is destroyed in the case of classes. Python is not very strict on scope as many other languages are, and therefore one must careful of declaring variables everywhere .Another reason why this might be dangerous is the fact that you can easily override a python variable, because assignment and declaration are identical.

x = 5
x = "Where did you find coconuts?"

As you might see, this is allowed, but can become very dangerous in Python programs, and so i'll say it again:NAME YOUR VARIABLES CAREFULLY WITH PREMEDITATION

Back to top


Errors And Exceptions

Introduction

When you program, you sometimes make a mistake. Programming mistakes include leaving out brackets, leaving out commas and other language requirements, or making a spelling error. Typo's are common in programming, and this is why most program compilers/interpreters will tell you you've made a mistake. The python interpreter will also tell you when youve made a mistake. So let's make one and see what happens:

print "I am sir lancelot

This is the output from the interpreter:

File "<stdin>", line 1
print "I am sir lancelot
^
SyntaxError: EOL while scanning single-quoted string

This is called a syntax error!

Syntax Errors

A syntax error is when you make mistake regarding the language semantics. If you leave out the last double quote, as in the preceding example, the interpreter generates a syntax error, because the string was not terminated with a corresponding double quote. Syntax errors in Python are much less common than in other languages, but they still occurr. All you need to do is read the error, go to the line number where the error occured and fix it.

Note: Sometimes the line number reported is not the culprit, but that is where the interpreter couldnt keep going anymore, if the line number where the error is reported seems correct, look up in your code and you might find the syntax error elsewhere

Logic Errors

Logic erros are much less obvious and are harder to find. A logic error is when the program runs, but it generates the wrong output. Here is an example of a logic error due to arithmetic being doen wrong:

myvar = 5 * 10 + 2
print "The output is 60 " + str(myvar)

The preceding example is stupid, but it illustrates how a logic error happens, logic can occur for many reasons. Here is a logic error that occurs due to statements being in the wrong sequence.

myMarks = [90.5]
myMarks.append(50.7)
print "My average is " + str(myMarks / 3.0)
myMarks.append(50)

If the print statement in the preceding example is put after the last append to the list, it will generate the correct output. However, we have put it in the wrong place, and thus the output will be incorrect. This might seem stupid now, but many logic errors occur because statements are not in the right sequence.Inifinite loops are also logic errors:

counter = 1
while counter > 0:
    counter += 1
    print "Looping without an end"

Hint: Remember that the compiler reads from top to bottom, just like a human being, meaning that the sequence of statements are very important

Exceptions

An exception is the reaction of the interpreter when it encounters something that is not provided for in the code. Here is an exmple of code that can create an exception:

mynumber = raw_input("Please enter a number")
print int(mynumber) / 5

Program output:

Please enter a number: anumber
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unsupported operand type(s) for /: 'str' and 'int'

When the user enters a string, instead of a number, the script dies. This is called a runtime error and it is also what happens to non python programs when a message box in windows pops up that says the program has crashed. This doesn't exclusively mean that it was generated by the above case, there are many reasons for runtime errors to occur. I will list a few here:

 

Handling Exceptions

An exception will always cause your script to stop excecuting, unless you handle it. Handling exceptions are a very important part of prgramming. So lets rewrite the number deviding program above to incorporate exception handling.

mynumber =  raw_input("Please enter a number: ")
try:
     mynumber = int(mynumber)
     print mynumber / 5
except:
     print "An error occured"

There are many types of exceptions, but were catching all of them, so if the user inputs an invalid value, it will print the string "An error has occurred"( I have provided this example in this file).But wouldn't we like to give more information on what went wrong? Lets rather catch only the right error this time, but with something extra:

mynumber = raw_input("Please enter a number: ")
try:
     mynumber = int(mynumber)
except ValueError:
     print "Not a valid number"
else:
      print
mynumber / 5

You can get this example here . Now we know which error we have caught, and we know how to respond. The else part of the exception specifies what needs to be done if the exception did not occurr, this just allows you to catch the right exception. It is a good idea to put volatile code in one big try clause, and then to catch each exception as you discover it.

Note: It is very important to consider which exceptions might occur in your programs, and it is also important to stress test your applications to see if you can make exceptions occur, and then go back to the code and add exception handling.


4. Control Structures (if... else for while)

4.1 The If Statement

The If statement is one of the single most important things you will learn in programming, and it is an indispensable tool for making decisions in a program, here is an example of an If statement:

# a program that illustrates the use of an if statement
age = raw_input("How old are you?")
if age == 16:
           print "You qualify for this competition "
else:
           print "You must be 16 to qualify for this competition "
# end of code

This if statement checks for equality, in other words it takes the value of age and compares it to the number 16. The same if statement can be expressed in reverse, to the same effect as "16 == age", but this contradicts the way most people write sentences and communicate, so more often you will see the form in the above program.
to summarize the operators for you:Read it from left to right , as in a is more than or equal to b.

>= More than or equal to
== Equal to
<= Less than or equal to
> More than
< Less than
!= Not equal to (C style)
<> Also not equal to (VB Style)

Quick note: ">=" and "=<" Are not the same thing, the latter form is incorrect, and will generate an error, the same rule applies to the "<=" operator. To make it simple for yourself, try reading what you are saying out loud, for instance: x >= 5 reads "x is larger than or equal to five".

In an if statement, everything evaluates to either True(yes) or False(no), which by the way are keywords in Python, so that the statement: "if True:" will always evaluate to true and the statement if False: will always be false, and the block of code in the if statement will never be reached, this is sometimes called unreachable code.

Note : Unreachable code is code in a program that can never be reached, an example of unreachable code would be code that comes after the program calls an exiting method.

Of course, an else is not mandatory and you can put an if statement within an if statement within an if statement:

if age > 16:
           if ticket == "valid": #we say that this if statement is nested inside the outer if statement
                        print "You may watch the movie "

This could have been one if statement:

if age > 16 and ticket == "valid":
       print "You may go in"

The and in the preceding if statement does exactly the same thing as nesting the previous if statement into the other did.

A little bit of confusion

The if statement below is unclear. why? Take a look at it, then run it.

if 50 < 100 == True:
         print age
else:
         print "false, 50 is more than 100?"

If you expected the output to be "false, 50 is more than 100", you were right. If you weren't guessing, your clever, unless your not learning for the first time. This if statement touches on the subject of boolean algebra.This is how it evaluates:

100 == True: yes, this part now becomes True to give you:
50 < True: True is then converted to an integer:
50 < 1:Then the statement is again evaluated
False:It turns out to be false, which in this case was not the intended meaning of the statement.

To find the answer to this pitfall programmers turn to math, or even the parenthesis used in math to show order of precedence. The python interpreter will evaluate the innermost parenthesis first. The correct form of the previous program would be:

if (50 < 100) == True:
         print age
else:
         print "false, 50 is more than 100?"

Now the code is both legible and precise. You should be careful with little details like these, and be aware of them when your program is malfunctioning.

4.1.2 How does and/or work?

With and both conditions need to be true for the whole expression to be true and this extends to more complex if statements such as:

if a > b and b < c and d > a:

In the preceding if statements if any conditions are false, the body of the statement will not be executed(in other words the code for the if statement will not be executed).

With or only one of the conditions in the if statement must be true for the statement to evaluate as true so

if a <b or b > 300 or True:

The above if statement will always be true, because of the "or True" part

You may also use order of precedence with and/or. here is an example:

if (score > 40 and score < 50) or ( score == 0 and absent):
         print "The student qualifies for the sick test"

Note that in the preceding code the variable absent can be a Boolean variable set to True, or any variable with a non-zero value to evaluate to true, and this is equal to ...

if (score > 40 and score < 50) or (score == 0 and absent == True ):
         print "The student qualifies for the sick test"

Boolean algebra can be expressed by using and as multiply and or as plus, thus the preceding if statement, given the value 45 would be

(1 * 1) + (0 * 0) = 1
given: 30
1*1+0*0

Quick Wisdom

If statements are very important, and constructing good if statements is a valuable skill. Always remember to keep your code clear and simple. Sometimes a little fancy footwork can give you some amazing results, but generally a whole lot of complexity will hurt the readability of your code, and make debugging quite a bit more difficult. It is neither impressive to spray one if statement across 20 lines nor do that same if statement in one line. You will start writing your best if statements after repeatedly having to go back to ones that didn't work. Also note that if statements are one of the first places where logic errors occur.

Homework : Read sections 2.3.2 , and 2.3.3 of the python documentation.

Back to top

4.2 The for loop

The for loop is used to repeat a set of statements a specified number of times. In python you can also use a for loop to loop through lists in order to process every item.Lets look at this concept in more depth

pets = ["dog","cat","hamster","goldfish","parrot"]
for pet in pets:
          print pet

Program output :

dog
cat
hamster
goldfish
parrot

Useless Note: this style of loop has also been called a for each loop" in some other languages.:

Is that it? Is it that simple? The answer is yes, but this for loop leaves allot to be desired, and C++/Java programmers will tell you that this loop only allows you to loop through the items of a list, which is insufficient in modern programming. Python has a simple solution to this problem:

for i in [1,2,3,4,5,6,7,8,9]:
       print "A traditional counting for loop, i is ", i

4.2.2 The range function

The previous code seems dumb, especially when you want to go up to 1 000, or 1 000 000. An that's why Python has a nice little builtin function called range that returns a list of integers in a range, so that:

for i in range(5):
        print i

Will print 0,1,2,3,4 to the screen.By default it will always start at zero, and increment by one .These defaults can be overridden in the following ways
range(1,4)         # output: [1,2,3] - 1 Is the starting point, four is the amount of iterations
range(0,30,5)   # output : [0, 5, 10, 15, 20, 25]
range(1,30,5)   # output : [1, 6, 11, 16, 21, 26]
range(1,30,-5)   # output : [] - You try counting from 1 to thirty in increments of -5, this is obviously invalid
range(30,1,-5) # output: [30, 25, 20, 15, 10, 5]

Study these examples, study the examples in the python docs, and experiment with this function if your still baffled.

Back to top

4.2 The while loop

The while loop will repeat a set of statements until the condition it was given becomes true.

password = ""
while password != "secret":
              password = raw_input("Please enter password: " )
print "Welcome to your account!"

 

Back to top


5. Functions

5.1 Introduction

Often it is necessary to repeat a set of statements in order to get the same functionality as previously discovered. Functions enable you to do this. Let me explain in a simpler way. You wanna make something that does something, every time you want it to :). Here is an example function:

def myFunc(num):
          print num**2
myFunc(5)
myFunc(int(raw_input("Enter a number to be squared: " )))

Analysis: The python def keyword is used to define a function, any function must be preceded by the def keyword. myFunc is the name of the function. This can be any valid identifier, for example:

Valid Function Names Invalid function Names Why?
SquareMy FunctionNo spaces in function names
my_little_func 12thFunctionFunction names cannot start with a number
aVeryLongFunctionName Short-Func

The "-" operator is invalid in a function name

checkIfAgeCorrect if May not use keywords as function names.

There are reasons why these rules exist, but I will not elaborate on that. I'm sure that you can think of why the interpreter doesn't like some of these functions. Further note that this is not a complete list, and there are many other examples of invalid function names.

What!?? Oh! I still haven't told you what functions do. The answer is this: Functions do whatever you want them to, and in which ever way you want them to do it. Another example might clarify this:

names = ["John","Jack","Jill"]
def isNameInList(nameToCheck):
      for name in names:
             if name == nameToCheck
                   return True
      return False
# The function definition ends here, where the indentation level returns back to where it was before the function, just like other compound statements
if isNameInList("Morris"):
        print "Morris is in the list!!!!"

This example contained some new information, and is one of the reasons why I had left functions until this late hour. Do you still remember True/False keywords from if statements? This is a similar situation, the only difference here is that we are using it in a function. The isNameinList function takes one argument, the name it should check for in the list. It then iterates through the list looking for the name, if it finds the name it then executes the return statement. That is, it exits the function and replaces the point where it was called with the value "True", the same goes for if it doesn't find the name, except that it will then substitute False in the place where it was called. To show you what the function did, I am going to show you where it puts the False from the preceding example:

if False:
        print "Morris is in the list!!!!"

This is only a representation of what was happening in the former example, so just remember that k? Functions are not limited to returning boolean values, and do not have to take arguments .Functions can return any data type. Here is a function that takes no arguments.

def showHelp():
      print """
              To calculate the winning lottery numbers, press 1
              To exit this program, press x
              """
showHelp() # were just testing our function here, note that you still have to provide the parenthesis, this is very important

5.2 Default arguments

Sometimes it's nice to write a function that does some thinking for you, but only when you want it to, default arguments are values that you define for an argument when your creating the function. When you later call that function and don't supply the arguments that have default arguments, the values you supplied will be used. Here is an example:

def createNewFile(fileName = "Untitled") :
       myFile = fileName
createNewFile() # the myFile variables value will now be "Untitled"
createNewFile("My famous brownie recipe") # the myFile variable will now contain the string: "My famous brownie recipe"

Note: Functions define their own scope, which means if you create a variable in a function it is unique to that function and cannot be used elsewhere. You can also create a variable of the same name in another scope, which means that your variables need not always be unique

Back to top


6. Modules

6. 1 What are modules?

Modules are essentially Python files that you create, but you can make a module that doesn't have executable statements. That is, you don't have to make a module that runs when you open it. Python allows you to create a module with functions and variables in it, that you can re-use in other modules. Let's make a module

#my first module
def modfunc():
    print "this function is executed from within the module"

def anotherFunc(name,surname):
    print name + " " + surname
#EOF

Copy this module's code into IDLE or into whichever editor your using, and save it as mymodule.py. Now we will create the second file( I have created this file already for your convenience, you can get it here)

#This is where we will use the module's functions
import mymodule

mymodule.modfunc()
mymodule.anotherFunc("Tjaart","Blignaut")
#EOF

You can name this file anything you like, I have named mine runmodule.py, you can download it if your too lazy to copy and paste, or if yours doesn't work for some reason.Note that in order to import a module it must be in your PYTHONPATH environment variable, or in the same directory as the script you have imported it from. You can now import the mymodule into any script you like, meaning that you can write a set of functions, and then make them re-usable.

6.2 The import statement

The import statement is used to import a module. It will first look in the directory where the script is located, and then it will move on to the PYTHONPATH environment variable directory, and search there. Here are some points to remember about the import statement:

The import statement is very flexible, and this is why this small section is so long winded. Here are some forms of the import statement and their explanations:

import Statement forms
form explanation
import module Just imports a module or package
from module import something

Only imports the specific function/class/variable from the module that is specified. it is then unneccesary to type module.something, you can just type something

from module import *

Import everything from the specified module, you can then access things in a module without out the module. prefix

import package.module as somethingElse Import a module from a package, but call it something else
import package.module Import only a specific submodule from a package

 

6.3 The builtin module

So far, I have indicated builtin python features by highlighting them like this, but these features also belong to module in python called the builtin module. You don't need to include this module as it is included in all your scripts by default.

6.4 Other Python modules

Python has many modules, and this tutorial is hardly the place to discuss them. I will show you one example module that uses the os module to list the contents of a directory:

#An example that lists the contents of a directory
import os

directoryListing = os.listdir("C:\") # this function returns a list of directories
for directory in directoryListing:
   print directory
#EOF

6.5 Batteries included

Python has quite a few very usefull modules that you get with your Python installation, and this makes Python very powerful. Be sure to check out the Python documentation, there are many examples in there, lots of explanations, and many many modules. Python is very well documented, which makes it even better than it already is. Always check if there is a module to do something before you try coding it yourself, youd be surprised at what you find. Also check out the Python cheese shop, where many third party modules and programs are.

Back to top


7. An introduction to Classes and Object Oriented Programming

7.1 Introduction

Before Object Oriented Programming, there was functional programming. C is a functional programing language. The problem with funtionla programming came when programs became increasingly complex. Let me illustrate with a simple example how you would go about soling a phonebook problem with functional programming, and then I will move on to an object oriented solution.

# A phonebook in a functional way
phoneBook = []

def addPhoneBookEntry(surname,name,phoneNumber):
     phoneBookEntry = { "surname" : surname, "name" : name, "number": phoneNumber }
     phoneBook.append(phoneBookEntry)

def findPersonByName(name):
     for entry in phoneBook:
             if entry["name"] == name:
             return entry

addPhoneBookEntry("Smith","John","205-555-546")
addPhoneBookEntry("Davis","Johnathan","205-432-246")
addPhoneBookEntry("Duke","Raoul","205-234-245")
addPhoneBookEntry("Darko","Donnie","205-666-236")
addPhoneBookEntry("Rezner","Trent","205-456-146")
addPhoneBookEntry("Cartman","Eric","205-654-746")

print findPersonByName("Donnie")["number"]

Here is the file for this program, you should however be able to code this by yourself by now. Now what if we wanted to create another phonebook, what would we do? This is a complex problem if you go about this same method of solving it. A little later in this chapter I will show you exactly how we can solve it with the PhoneBook class.

What is a class?

Classes are about describing a set of similiar things. With a class you don't only describe the properties of something, but also what it consists of, and what it is capable of. You can also create a hierarchy of classification. For instance you can say that an SUV is a car is a vehicle, and then reuse the vehicle classification to by saying a mountain bike is a bicycle is a vehicle.

 

myList.append("spam")

myList was an instance of a list object, and append is an object method. You are adding to the list, but the list is doing all the work. Get it?

Objects

We say that an object is an instance of a class. Before you create an instance of the class, there is only a description of what an object is like in memory. Then when you finally create an object that description or blueprint is used to instantiate a new instance of that class, this is called an object.

Revisitting the phonebook example

We will now redo the phonebook example, but this time we will create a class. It is after all, about time you learnt how to make an object.

# An object oriented phonebook
class
PhoneBook:
       def __init__(self):
             self.__entries = []
       def addEntry(self, surname, name, phoneNumber):
             entry = { "surname" : surname, "name" : name, "number": phoneNumber }
             self.__entries.append(entry)
       def findPersonByName(self,name):
             for entry in self.__entries:
                    if entry["name"] == name:
                           return entry
       def getNumber(self,name):
             return self.findPersonByName(name)["number"]

friends = PhoneBook()
friends.addEntry("Diggity","Snipiddy","342526")
friends.addEntry("Jones","Dilbert","1234567")
print friends.getNumber("Dilbert"              

As you can see I created an instance of the PhoneBook class when I made the friends object.So let's get to the syntax here. The class keyword is used to define a class, there is no other way to do it. in the friends = PhoneBook() statement the init method of the class is called and the object is created in memory, an __init__() method does this and is used for this particular reason. This __init__() method is called a constructor.

The self paramater is Python specific syntax. self is the object your working with, note also that self is just the status quo. You can name the first init parameter anything. As you may have noticed I have added the self parameter to every object method, so that I can access the members of the object: self.__entries.append(entry)

A double underscore indicates that a method or variable is private. This simply means that whoever is creating the object cannot modify that paramater. It is generally advised to make all data memebers(variables) of the class private, and to create public(without __) methods to access and change them. This way you have more control over what people can do with the innerworkings of the object. The last thing you want is for an object to stop functioning because someone was able to change something that shouldnt have been changed.

For example, if you have a class that keeps track of your CD collection, it might automatically generate a code for each cd, write the code to a file and put it on the cd, and then write itself(the whole object) into a file so that you can later retrieve the object. If by fault, the program that uses your object changes the code for the object after the file has been written to the cd, the accuracy of the program decreases.

 

Back to top


The End... Finally

Ill fix the problems in this file as soon as i get the chance, okay!

As a closing note I'd like to wish you luck on your programming endeavours, and all others. Writing this tutorial has been an enlightening experience. I have learnt things that I didn't know about Python. Now before you go and write a kick ass program, your probably wondering why Python is so easy and what are you trading up for it. If it's so good, there must be some bad involved.

The truth about python is that it isn't language that will produce high speed applications, and thus it isn't a good idea to write an enterprise database server or anything too high load in it. However you can do sections of your high performance programs in Python. Some things don't need to be fast, and the differences in speed are neglible. Memory is another trade off, Python uses quite a bit of memory, the text editor I wrote in Python was 16 megabytes in memory, which is ugly for one window, a menu, and a text control. Python may very well be the way of the future though, because when 16 megabytes memory becomes peanuts, python will rule the jungle.

Where to next?

When I first started programming, I had some very good ideas for applications, they were swirling through my head, all i needed was a vehicle language to write them in. None of these programs realised, because my interest swayed from programming as it was a whole lot of everything, for a whole lot of nothing. API's are the key to the dilemna that you know a programming language, but you don't know how to do everything. It is very rare that you will write a usefull program without actually using something someone else did. Just as you wouldnt build your own computer chip. Search online for python modules, check out the python website, And keep an eye on this site too.

Hopefully soon I will bring you my next Python tutorial. "The Python chef's Guide", which will include information on how to make executables/binaries from your python source,windowed programs with wxPython, and some little recipes and general solutions.

Written By Tjaart Blignaut

Peace :P

 


Forward >>

Get Firefox!    Valid HTML 4.01!

©2006 Tjaart Blignaut