Login

Getting Started With Python

Yes, Python is a type of snake, but it’s also a little-known scripting language that you can use to create entire web sites. In this article Martin introduces us to the wonderful world of Python…For those of you who haven’t heard about it, Python is a high-level scripting language. This tutorial will guide you through the process of downloading, installing, and running your first Python script.

Python is a somewhat unpopular language that is often compared to Perl (from people who know it exists). So what exactly is Python? Well, put simply, it’s a scripting language. This means that it is interpreted rather than compiled, so it saves time during debugging and early development, just like PHP.

You can write entire web sites, and even command-line applications with Python. It runs on both Windows and Linux, and is quite simple to master once you know the basics, which are what I will teach you today.

Anyhow, let’s get started…{mospagebreak title=How Do I Get Python?&toc=1} You can download it for free from Python’s web site. It’s open source, so you can even modify its source code if you know C. There are source and precompiled binaries available for both Linux and Windows.

How Do I Install Python?If you want to install the Windows version of Python, you just run the graphic installer and select some options. If you compile it for Linux/Unix then you’ll have to do the usual three steps to complete it:

./configure make make install

The last one usually needs to be run with root user privledges. You may also want to compile tk-inter support in, like this:

./configure –with-tk

How Do I Run Python?If you want to check something simple, run the Python interpreter by typing

python

…or following the Python shortcut in Windows. The interpreter isn’t very useful for large pieces of code, so generally you would want to use your favourite text editor to create the scripts and then execute them.

How Do I Execute a Saved Script?This depends on your which operating system you are using:

Linux/UnixPut

#!/usr/bin/env python

… at the top of the script and CHMOD it to have execute permissions, like this:

chmod +x foobar.py

If you want to run the script as a CGI (from a web server) then you should use #!/usr/local/bin/python or #!/usr/bin/python, depending on the system configuration.

To find out where Python is installed on your Linux web server, just type

where python

… at the command line.

Windows NT/2000Run cmd.exe. If the .py extension is registered from the Python interpreter then you simply type the filename at the command prompt and Windows will associate it with Python and automatically execute it for you.

Windows 9x/MEYou can simply type

python foobar.py

…at the command prompt if the python binary is in your path. If it isn’t, then you will need to change into the Python directory and run it from there.

Which editor should you use for writing your Python scripts? It doesn’t really matter, although one with syntax highlighting is preferred. Checkout HTML-Kit if you will be creating your scripts on Windows.

Enough Talk, Let’s Start Coding!Scripting languages such as PHP and Perl separate commands using semi-colons, brackets, etc. Python identifies a statement by indentation only. This is an important point, so make sure that you remember it!

Here’s a basic Python script:

#!/usr/bin/python

# This is a comment # comments can span one line only

print ‘Hello world!’ print “Hello world!”

You can delimit strings with single or double quotes – it doesn’t make any difference to Python. If you want to write a string on more than one line then you can escape the end of the line with a backslash:

foo = “I’m a very long string which spans multiple lines” print foo

…or use HereDoc syntax with “”” or ”':

foo = “””I am a really long comment but it doesn’t matter no backslashes are needed “””

You can also directly access single characters or slices from a string:

foo = “Hello” print foo[1] # outputs “e” since indexing starts at 0 print foo[1:] # ello print foo[-1:] # o print foo[2:4] # ll{mospagebreak title=Control Structures&toc=1} As with all other scripting languages, Python has its own set of control structures that allow you to determine a path thru which the execution of a script will proceed:

This example will loop through the numbers from 0 to 10 and test if the number is odd or even. The modulus operator (%) is used to calculate the remainder left after dividing the number by two.

This same example can also be rewritten as a while loop.

i = 0

while i <= 10 : if i % 2 == 0 : print str(i) + ‘ is an even number’ else : print str(i) + ‘ is an odd number’ i += 1

i = ‘Hello world’ print i

This example also shows that even though Python’s variables are loosely typed (you can assign any type of data to a single variable), you do have to convert them to a single type if you want to operate on different kind of variables.

To save the space that print adds between different parameters passed to it, you also have to add it to the string (when using string concatenation).

Command-line ParametersIf you want to pass parameters from the command line to your Python script, then you will need the sys module, which is imported on the first line of the example shown below. The module defines the argv list, which, as all of you C/C++ programmers will know, contains the arguments that are passed from the command-line to the script:

import sys

print sys.argv[0] # prints the filename of your script print sys.argv[1] # and the first parameter print sys.argv[1:] # or all parameters{mospagebreak title=Conclusion&toc=1} I don’t want to confuse you too much in this first article, so I’ll leave it at that for now. Take what you’ve learnt in this article and see if you can master the basics of writing a simply Python script or two.

Some useful reference sites that you might want to take a look at are: