Python

A basic overview and information about the Python language.


General


Python is a dynamic object-oriented programming language.  It is often referred to as a scripting language,  but is not limited simply to scripting.  Python features an extensive standard library that has many useful modules.  Information about the standard library can be found in the Python Reference Manual.

Philosophy

The philosophy behind Python focuses on simplicity and readability above all.  Python also set out to be more readable than Perl and avoid what it's creators considered to be difficult to read scripts.  Also, Python strives to one and preferably only one good way to do things.  All of these beliefs are summed up by Tim Peters in The Zen of Python.  Which can be read by entering import this into the Python shell it reads:

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!


History


Origin

Python was created created by Guido van Rossum.  The language was written primarily out of boredom and also the desire to replace the ABC language with a newer language. Over a Christmas in 1989, Guido decided he needed a hobby prject It is named for Monty Python's Flying Circus, a popular television show. 

Implementations


CPython


CPython is the standard implementation of Python. It is implemented in the C programming language. The Python language does not have a defining standards document, so CPython serves as the standard. CPython is also the original and most widely used implementation. It is the implementation created and maintained by Guido van Rossum. The official website of CPython is www.python.org


Jython


Jython is an implementation of Python written by Jim Hugunin in 1997. Jython is written almost entirely in Java and compiles to Java Byte Code. Using Jython, programmers have access to almost all of Java's modules including SWING and AWT. Due to the fact that it compiles as Java Byte Code, Jython can run on any platform with a JVM. For more information see www.jython.org


Iron Python


IronPython is an implementation of Python written entirely in C# and designed to run on the Microsoft .Net Framework. Version 1.0 was first released in 2006 and the current version is 1.1. IronPython strives to be compatabile with CPython, and is in almost all regards. There are some minor differences. IronPython compiles to Microsoft Intermediate Language and can be run on the .Net platform. For more information see http://www.codeplex.com/IronPython

PyPy


PyPy is essentially an attempt to implement Python in Python.  At first this seems strange and almost contradictory, however it soon becomes apparent that such an implementation would be quite powerful.  The goal is to remove the need to worry about lower level details from Python implementations.  The project also seeks to enable Python to introduce new features faster and be ported to new platforms faster.  There are even some rumors around that PyPy seeks to make a Python implementation faster than CPython.  For more information see http://codespeak.net/pypy/dist/pypy/doc/home.html


Syntax


Variables


Dynamic Typing

Python is a strongly typed dynamic language.  This means that variables do have types associated with them at any time, but also means these types can be changed over time.  All types are implicitly assigned in Python, unless an explicit type cast is used.
This means that variable types can be changed at any time throughout the program.
For example consider these assignment statements

x=3
print type(x)
x="hello"
print type(x)
x=5.5
print type(x)
The output of this code will read:
<type int="">
<type str="">
<type float="">
From this we can see x's type dynamically and implicitly changing with each assignment. In a statically typed language such as C or Java, this would be illegal and result in a compiler error in most cases.

Definition


Variables must still be defined before they may be used.  This is simply done with an assignment statement.  If an undefined variable is used a run time error occurs.  For example run the following:

print testVar
The output will be:

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    print testVar
NameError: name 'testVar' is not defined
If instead a value had first been assigned to testVar, there would be no error.

Type Casting


Sometimes, it is nessecary to force a variable to be a certain type.  This is done with an explicit type cast using one of Python's built in casting functions.  For example, consider the following code:

x=3
print x, type(x)
x=float(x)
print x, type(x)

The output of this code is:

3 <type 'int'>
3.0 <type 'float'>
After this code executes, x now has a type of float instead of its previous type of int.  However, because these types are immutable or unchangeable, what really happens is a new object is created of type float from x and then this object is assigned the name x.

Indentation

One of the most controversial features of Python is it's use of whitespace and indentation levels to determine scope.  Unlike C style languages, Python does not use {} to indicate blocks.  Instead, indentation levels are used to indicate blocks.

For example, the following is an if statement in Python using indentation to denote the block:


print "This is the code before the if"
x=3

if x==3:
    print "inside the if"
else:
    print "Else"

print "This is the code after the if"

In the above code, the indentation and whitespace define an if block and an else block.  The same is done for functions, classes, and exception handling.


Functions


Functions are defined using the def statement.  With this statement, a function is given a name and a list of input parameters.  Functions in Python do not have defined return types, but can still return values.  Functions are called by name and must be passed their parameters.

For example the function sum takes two inputs a and b.  The function then performs addition on these two inputs and returns the value.

def sum(a,b):
    return a + b

print sum(2,3)
print sum('h','i')
The output:

5
hi
Additionally, functions are not required to take input parameters or return a value.  When a function does not have a return value, it returns None. None is equivalent to null in many other languages and simply represents nothing or no value.

Classes


Python is also an object oriented language and as such supports the object oriented concept of classes.  A class, which is short for classification, is simply a type of object or thing.  It has various properties and abilities associated with it.  In Python, classes may have attributes(variables) and methods(functions).  Classes may also inherit traits from other classes.  The main difference between Python and many other languages that support classes, is that Python does not have visibility such as public and private.

To explain classes, look at this simple example of a class.  This class defines Balls, which have a color and an x and y position on some sort of grid. 

class ball:
    def __init__(self,color,xposition,yposition):
        self.color = color
        self.xposition = xposition
        self.yposition = yposition

    def move(self,distX,distY):
        self.xposition  += distX
        self.yposition  += distY

    def showInfo(self):
        print "The ", self.color, " ball is at (", self.xposition, ",", self.yposition, ")"

b = ball("blue",5,10)

b.showInfo()
b.move(5,-5)
b.showInfo()
b.color = "green"
b.showInfo()

The Mysterious Self


What is this strange self that the code above keeps referencing?  Well, self is really just what it sounds like, a reference to itself.  You see we can have more than one object of each class.  We could have thousands of balls if we wanted.  What self does is simply refers to this particular ball's attributes and methods.  It is primarily used for scope as well.  In move, there are two variables called xposition, one inthe scope of the class and one in the scope of the function.  Self simply tells Python that this xposition refers to the one in the ball's scope, not the one passed in.  In other words, it refers to the one that is connected to the ball, not the one passed in.


Constructors


Classes begin with one or more constructors.  These are the functions that build new objects of a class type.  In Python these must be declared with the name __init(self)__  they may also take parameters.  In this case our constructor takes 4 parameters: self, color, xposition, yposition.  These indicate what color the ball is and whete it is in our grid.  In this example a ball is created that is blue and is at (5,10) on the grid.


In Object Oriented Programming, a constructor allows us to create a new object, we see this above on the line that reads:
    b = ball("blue",5,10)
this line created a new object of type Ball and assigns it to the variable b.  We can make as many Ball objects as we want this way and store them to different variables.

The Shell


Python comes standard with an interactive shell that is helpful for learning the language and just testing ideas or concepts.  To run it you need to first download Python, go to http://python.org/download/ and download Python for your system.  Once downloaded, follow the instructions on the site for installation.  Once installed open a terminal window or command prompt and simply enter "python"  you may have to include the path to python such as "C:\Program Files\Python2.6\python" or similar.   You should see the following:

Python shell as seen on Ubuntu Linux

From here, any python code can be entered and run.  Please note this code will not be saved and is lost when the shell is closed.  Let's enter some code into the shell to see what happens.  Enter the Ball class above into the shell, remember to indent where needed.


Python shell with ball class entered

Now that we have defined the ball class, we can create an object and test out our code.  Try creating a ball and changing it's location.  Call the showInfo method to see the changes occur.  An example is shown below.

Python shell creating and manipulating ball objects, some errors shown.

As you can see above, when something is entered incorrectly, the shell returns an error.  These are the same errors a Python file containing the code would show when run.  You can continue to experiment with the shell, when finished it is time to save and run scripts.

Saving and Running Code

Python source code is saved in files with a .py extension.  Once saved in this way, it can then be run by the Python interpreter.  Python, unlinke C, is an interpreted language.  This means that you simple create a fil with a .py extension and run it.  Open your favorite text editior, and enter the following code into it(yes it is the same as above):

class ball:
    def __init__(self,color,xposition,yposition):
        self.color = color
        self.xposition = xposition
        self.yposition = yposition

    def move(self,distX,distY):
        self.xposition  += distX
        self.yposition  += distY

    def showInfo(self):
        print "The ", self.color, " ball is at (", self.xposition, ",", self.yposition, ")"

b = ball("blue",5,10)

b.showInfo()
b.move(5,-5)
b.showInfo()
b.color = "green"
b.showInfo()

Save the file as ball.py. Now, once again open a terminal or command prompt, this time browse to the files location.  Once there enter "python ball.py" to run the code, your ouput should look like the following:

The output of running the code.
Any Python file can be run the same, if errors are encountered they will be listed with a line number to help with fixing them.


The .pyc File


You may notice that after running ball.py, there is a new file in the directory called ball.pyc this file is a compiled Python file.  I know what you are thinking, you're saying "but wait you said Python was interpreted, not compiled!"  and this is true, it is interpreted, it is not compiled to machine code or assembly code.  This file is simply compiled to an platform independent byte code, this is similar to how Java is compiled if you are familar with it.  When a Python file is run, the Python Interpreter first checks if a compiled file exists, if it does, it then checks to see if it's date matches that of the .py file.  If the .pyc file doesn't exist or the .py file is newer than it, a new .pyc file is created.  You don't have to worry about these details much, just know that Python compiles your file to byte code as needed.  This is done to increase performance.

Next Steps

This is all the further I would like to take this brief overview of Python.  You now have a basic understanding of Python and how to run it.  You are now ready to take some further steps, I suggest the following resources:

Python Beginer's Guide - A guide to help those new to Python
Python Language Reference - Python documentation that shows all of Pythons available functionality
Learning Python - A greate book about Python

Comments

Improper use of the term "casting"

When you pass an object to one of the type's contructors it is not a cast but a new object. Casting is simply treating an object as a different type. In Python's case it is a brand new object, not a re-interpretation of an existing one.

Last edited Jan 17, 2009 6:16 AM
Report abusive comment
Jon Parise
Jon Parise
Software Engineer at General Dyanmics C4 systems Viz
Pittsburgh, PA

Contributors

Article rating:
Your rating:

Categories

Based on community consensus.

Activity for this knol

This week:

17pageviews

Totals:

1815pageviews
7comments