With the final release of Python 2.5 nosotros thought it was about time Builder AU gave our readers an overview of the pop programming language. Architect AU'southward Nick Gibson has stepped upwards to the plate to write this introductory commodity for beginners.

Python is a high level, dynamic, object-oriented programming language similiar in some means to both Java and Perl, which runs on a diversity of platforms including Windows, Linux, Unix and mobile devices. Created over 15 years ago equally an awarding specific scripting linguistic communication, Python is now a serious choice for scripting and dynamic content frameworks. In fact it is being used past some of the world's dynamic programming shops including NASA and Google, among others. Python is too the language behind Spider web development frameworks Zope and Django. With a salubrious growth rate now could be the perfect fourth dimension to add Python to your tool belt. This quickstart guide volition give y'all an overview of the basics of Python, from variables and control menstruum statements to exceptions and file input and output. In subsequent articles I'll build upon this foundation and offer more complex and specific code and communication for using Python in existent earth development.

Why learn Python?

  • It's versatile: Python can be used equally a scripting language, the "glue" that sticks other components together in a software arrangement, much in the same way as Perl. It can be used as an applications development language, merely like Coffee or C#. It tin be used as a Spider web development linguistic communication, similiarly to how yous'd use PHP. Any you demand to do, chances are you can use Python.
  • It's costless: Python is fully open source, meaning that its free to download and completely costless to use, throw in a range of complimentary tools and IDE's and you lot can get started in Python evolution on a shoestring.
  • It's stable: Python has been effectually for more than fifteen years at present, which makes it older than Java, and despite regular development it has only only has reached version two.5. Any lawmaking you write at present will work with future versions of Python for a long fourth dimension.
  • It plays well with others: It'due south easy to integrate Python lawmaking with C or Java code, through SWIG for C and Jython for Java, which allows Python code to call C or Java functions and vice versa. This means that you can incorporate Python in electric current projects, or embed C into your Python projects whenever you lot need a fiddling extra speed.
  • It's like shooting fish in a barrel to acquire and utilize: Python's syntax closely resembles pseudo code, meaning that writing Python code is straightforward. This also makes Python a great pick for rapid application development and prototyping, due to the decrease in development time.
  • It'south like shooting fish in a barrel to read: It's a elementary concept, a language that is like shooting fish in a barrel to write should also be easy to read, which makes it easier for Python developers to work together.

Okay, plenty already, I'm sold. Where do I become it?

Easy, in fact if y'all're running Mac or Unix, chances you've already got information technology, merely pull up a last and type "python" to load up the interpreter. If you don't take it, or you're looking to upgrade to the latest version head on over to the download page.

Alternatively you could install ActivePython, a binary python distribution that smooths out many of the hassles. There is a graphical installer under nigh platforms, all that you need to do is click through the dialogues, setting the install path and components. In Windows, you can then start up the interpreter by browsing to its entry in the start menu, or on any arrangement simply by typing 'python' in a terminal. While ActivePython is generally easier to set, it tends to lag backside official Python releases, and at the fourth dimension of writing is only bachelor for Python 2.iv.

Interactive Mode

Now it's time to load upwards the interpreter in interactive fashion, this gives you a prompt, similiar to a command line where y'all can run Python expressions. This lets y'all run elementary expressions without having to write a Python plan every time, let'south try this out:

Python 2.5 (r25:51908, Oct 6 2006, 15:24:43) [GCC four.1.2 20060928 (prerelease) (Ubuntu 4.one.1-13ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more data. >>> print "Hello World" Hello World >>>            

The first 2 lines are the Python environment information, and are specific to my install, so your mileage may vary. Interactive style is useful for more than just friendly greetings even so, it also makes a handy calculator in a compression, and being part of a programming language allows you to use intermediate variables for more complicated calculations.

>>> two+ii 4 >>> ii.223213 * 653.9232 1453.8105592415998 >>> x,y = 5,twenty >>> x + y 25 >>> revenue enhancement = 52000 * (viii.five/100) >>> print tax 4420.0 >>> "how-do-you-do" + "world" 'helloworld' >>> "ring " * 7 'ring band ring ring band ring ring '            

Some other Python type that is useful to know is the list; a sequence of other types in society. Lists can be added and multiplied like strings, and can also be indexed and cutting into sublists, chosen slices:

>>> x = [i,2,3,four,v,6,seven,8,9,x] >>> x [1, 2, 3, four, 5, 6, vii, 8, 9, 10] >>> 10 + [eleven] [1, two, three, iv, five, vi, 7, viii, nine, 10, 11] >>> x + [12] * 2 [1, two, three, 4, 5, 6, vii, 8, 9, 10, 12, 12] >>> x[0], x[1], x[9] (1, 2, x) >>> 10[1:3], x[4:], 10[two:-two] ([two, 3], [v, half dozen, 7, 8, 9, 10], [3, iv, 5, 6, 7, eight]) >>> 10[:] [1, 2, iii, four, 5, six, seven, 8, ix, 10]            

The interactive manner is expert for quick and dirty calculations, but once you start writing anything longer than a couple lines, or yous would like to salvage your programs to use again afterward, information technology's time to let it go and commencement writing python programs. Thankfully this is easy, merely type your commands into a .py file and run information technology with the same control.

Command Menses

Just like your favourite programming language, Python has all the usual ways of controlling the execution of programs through if, while and for statements. In Python, an if statement looks like this:

if a > b:  print a else:  print b            

Yous'll see that unlike languages such as C or Java, Python does not use braces to group statements together. Instead statements are grouped together by how far they are indented from the margin, the torso of a statement extends for as long every bit at that place are lines below it with the aforementioned or greater indentation.

ten = 3 y = 4 if x > y:  10 = x + ane  y = y + 1            

For example, in the above lawmaking 10 = 3 and y = four at the cease of the program.

10 = 3 y = 4 if 10 > y:  10 = x + 1 y = y + i            

In the second case, however, y finishes equal to v.

Python likewise has loops, both of the while and for variety. While loops are straightforward:

while a > b:  a = a + ane            

For loops work a picayune differently from what you might be used to from programming in other languages, rather than increasing a counter they iterate over sucessive items in a sequence, similiar to a Perl or PHP foreach. If you practice need to have that counter its no problem, y'all can apply the built-in range function to generate a list of numbers like so:

for i in range(10):  print i            

If you need it, you can have finer control over your loops in Python past using either pause or continue statements. A continue statement jumps execution to the top of the loop, whilst a pause statement finishes the loop prematurely.

for 10 in range(10):  if x % 2 == 0:  proceed  if ten > 6:  break;  impress x            

This code will produce the following output:

1 iii 5            

A real program: true cat

At present we almost have the tools at our disposal to write a consummate, admitting small, program, such as the common unix filter cat (or type in Windows). cat takes the names of text files as arguments and prints their contents, or if no filenames are given, repeats user input back into the terminal. Earlier we can write this program notwithstanding, we need to introduce a few new things:

Opening and reading files.

In Python files are objects similar whatever other type, and accept methods for reading and writing. Say for case we accept a file chosen lines.txt which contains the post-obit:

line1 line2 line3            

There are ii main ways nosotros can view the contents of this file, by character or past line. The following code demonstrates the deviation:

>>> lines1 = file("lines.txt") >>> lines1.read() 'line1\nline2\nline3\northward' >>> lines2 = file("lines.txt") >>> lines2.readlines() ['line1\n', 'line2\due north', 'line3\n']            

The read() method of a file object reads the file into a string, whilst the readlines() method returns a list of strings, i per line. Information technology is possible to take finer command over file objects, for example reading less than the entire file into memory at one time, for more than data see the python library documentation (http://docs.python.org/lib/bltin-file-objects.html).

Importing modules and querying command line arguments.

Python comes with a wide variety of library modules containing functions for commonly used tasks, such as cord and text processing, back up for common net protocols, operating system operations and file compression – a complete list of standard library modules can exist found here http://docs.python.org/lib/lib.html. In order to use these functions you must import their module into your programs namespace,
like and then:

>>> import math >>> math.sin(math.radians(60)) 0.8660254037844386            

In this example you tin run across that we refer to the imported functions past their module name (ie. math.sin). If yous are planning to use a module a lot and don't want to go to the trouble of typing it's module name every time you utilise it and so you can import the module similar this:

>>> from math import * >>> sin(radians(lx)) 0.8660254037844386            

Access to control line arguments is in another module: sys, which provides access to the python interpreter. Command line arguments are kept in a list in this module called argv, the following example demonstrates a plan that but prints out all the command line arguments i per line.

import sys for argument in sys.argv:  print argument            

This produces the following output when run with multiple arguments, the showtime argument is ever the proper noun of the script.

% python args.py many command line arguments args.py many command line arguments            

Input from the console

It seems maybe a little primitive in the era of GUIs and Spider web delivered content, but console input is a necessity for whatever program that is intended to be used with pipes. Python has a number of methods for dealing with input depending on the corporeality of command you need over the standard input buffer, however for most purposes a simple call to raw_input() will do. raw_input() works just similar a readline in C or Java, capturing each character until a newline and returning a cord containing them, like then:

name = raw_input() print "Howdy ", name            

Error handling with exceptions

When you're a developer, runtime errors are a fact of life; even the best and most robust code can be susceptible to user error, hardware failures or merely conditions you haven't thought of. For this reason, Python, like nigh modern languages, provides runtime fault handling via exceptions. Exceptions have the advantage that they can exist raised at one level of the program and then caught further upwards the stack, meaning that errors that may be irretrievable at a deep level but can be dealt with elsewhere need non crash the program. Using exceptions in Python is simple:

try:  filename = raw_input()  filehandle = file(filename)  print len(filehandle.readlines()) except EOFErrror:  impress "No filename specified" except IOError:  impress filename, ": cannot exist opened"            

In this case, a block of code is placed inside a effort statement, indicating that exceptions may be raised during the execution of the block. Then two types of exceptions are defenseless, the first EOFError, is raised when the raw_input() telephone call reaches an end of line character earlier a newline, the 2nd, IOError is raised when there is a problem opening the file. In either case if an exception is raised then the line that prints the number of lines in the file will not be reached. If whatsoever other exceptions are raised other than the two named, and then they will exist passed up to a higher level of the stack. Exceptions are such a clean way to bargain with runtime errors that soon plenty you'll be wanting to heighten them in your own functions, and you'll be pleased to know that this is easy enough in Python.

attempt:  raise ValueError, "Invalid type" except ValueError:  print "Exception Caught"            

The Final Production

Now that y'all've got all the tools at your disposal to write our filter. Let's take a expect at the program in full first, before reading on, put your new knowledge to use by working out what each line does:

import sys  if len(sys.argv) < ii:  while i:  try:  line = raw_input()  except:  break  print line else:  for filename in sys.argv[one:]:  try:  file_contents = open(filename).read()  print file_contents,  except IOError:  print "Error: Cannot open", filename            

The program is simple, if there are no control line arguments (except for the script name, of course), and so the program starts reading lines from the console until an interrupt is given. If at that place are command line arguments, then they are opened and printed in order.

So there you take information technology, Python in a nutshell. For my next article I'll exist walking yous through the evolution of a Python program for finding all of the images used on a spider web page. If you'd similar to suggest a topic for me to encompass on Python drop me a line at nick.gibson@builderau.com.au.