The Python Programming Language

Posted by: Rea Maor In: Programming - Wednesday, May 2nd, 2007

We’re going to skip several language generations ahead and visit a world where you just tell the computer what to do, and it does it. Without having to explain to it what a string variable is and how many bytes to allocate for its storage every time.

Python, print “hello world!”


Python 2.4.3 (#1, Jul 26 2006, 20:13:39)
[GCC 3.4.6] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print "hello world"
hello world
>>>

Not bad. Can you store it in a variable?


>>> greet="hello world"
>>> greet
'hello world'

Hey, I didn’t have to tell it that ‘greet’ is a string! Does it work for multiple strings?


>>> greet1="hello "
>>> greet2="world!"
>>> full_greeting=greet1+greet2
>>> full_greeting
'hello world!'

Yup. What about other variables?


>>> greet1=999
>>> greet2=1
>>> full_greeting=greet1+greet2
>>> full_greeting
1000

We just reused a variable name, changing it from a string to a number, and Python didn’t even blink! A C compiler would be all “ERROR: assignment to incompatible variable type” by now. How about treating a string like an object?


>>> greet="hello world!"
>>> greet.replace("world","Mars")
'hello Mars!'
>>> (greet.split(" "))[1]
'world!'
>>> greet[0:8]
'hello wo'

See, we have these string object methods that all work with our string variable now, because they get inherited to every string object. This is built-in; no need to include libraries, allocate memory, or declare an object template – just call it into existence and it is so. You don’t even have to name it:


>>> "hello "*3+"world"
'hello hello hello world'

What’s more, you don’t have to compile it! Python is a scripting language, which means you can’t do jack without the Python engine. It’s free to download and use, for any purpose, and exists for Windows, Unix, Mac, and most other major platforms. What I’ve been showing you is the interactive mode, where you just call ‘python’ from the command line and type in instructions one line at a time – this is called the “interpreter”. To do a whole program proper, here’s an example:


#!/usr/bin/env python

import random

number_record = []
stopflag = 0
while (stopflag == 0):
number = random.randint(1,365)
for n in number_record:
if (n == number):
stopflag = 1
stop_number = n
number_record.append(number)

print number_record
print "Length of trial:", len(number_record)

This is a proof for the Birthday Paradox. It picks a random “date” number between 1 and 365, then goes on picking more of the same, checking if there’s a match and adding it to the list. It stops when it finds a match and prints the results of the experiment. Repeated trials will show that indeed, you can find a match for 1 in 365 in less than 23 picks more than 50% of the time. The output from one run:


[298, 182, 150, 10, 190, 43, 31, 318, 298]
Length of trial: 9

Yes, that’s a “list” object. A list is a fundamental data type included in many scripting languages. A list would require a phenomenal amount of code in C, C++, and other low-level languages, but it’s second nature in a scripting language. As for the “program”, it’s just plain old text saved to a file and called as an executable. The script gets handed to Python, and it runs it just like it was a compiled program. This is another reason why scripting languages are so much easier than compiled languages; you just write and run, editing the file and running it immediately to test the output.

Fast, here’s a basic run-through of Python:

Note the structure of the above code listing. Python uses spaces, tabs, and newlines to designate code blocks where C would use semi-colons and curly braces. So, Python is white-space sensitive. That puts some programmers off, but really you get used to it after writing twenty lines. You just indent your code like you normally would and Python figures it out from there.

Comments:


""" A function to compute the terminal's display area. """

#
# They grilled me on this program during the audit.
# I wasn't expecting a Spanish Inquisition!
#

Comments can be either preceded with a pound sign, or enclosed in triple quotes. With the triple quotes, you can also use the comment as a documentation string, for when the user asks for help. Try typing “help(list)” to get documentation on the list object.

Data Declarations:


x = 91
calories = 125.25
flavor = "Vanilla"
animals = ("fish", "horse", "frog")

Output statement:


print "I'm bored!"
print animals[1]

In the lower line, the ‘animals’ list we just created will print ‘horse’, because its the second (counting from 0!) item in the animals list (actually a tuple, which is an immutable list!).

Input statement:


age = int(input("How old are you?"))

This will print a prompt asking the user to type in their age, and store the input in the ‘age’ variable. Because the user might be a smart aleck or type in something like “I’m 37, I’m not old!”, we specify that Python is to accept only numeric input here.

Math:


z = x + y
z = (50-5*6)/4

File access:


f = open(mydiary, "r")
embarrassing_secret = f.read(1)

First, we create a file access variable for read mode. Then, since Python treats a file just like a list of strings, we call data from the file just like it was a list!

Conditional statements:


if speech > (4 * hours):
print "yawwwwwwn!"

Fixed iteration:


for i in range(len(deck)):
draw_card()

Here, we assume you started with a deck list. The “len” grabs the length of this list, and the “range” function makes a list from 1 to the list-length.

Conditional iteration:


while hour < 10:
while station != 107.2:
while decibals < 5000:
play_radio()

Three nested “while”s here, testing three variables before repeating the function.

Libraries:


import string

Would include the “string” library of extended functions.

Functions:


def talk(response):
print response

You define a function with “def”, then type in whatever code will execute when you call it. The part in parenthesis is an “argument” passed to the function, just like in any language that uses function parameters.

These are just the basics. There’s much, much more to Python, and in fact it has a reputation for scaling up very nicely; making it suitable for enterprise-level applications such as BitTorrent and Blender. Eric S. Raymond, the noted tribal bard of the “hacker” lifestyle, is an outspoken champion of Python.

With all the power and ease of use that scripting languages afford, you might well ask, “Why do we even still have C?” In a word: performance. Compiled programs run faster than scripting language programs, because you’re only using the code you need in a compiled program, while a scripting language drags the whole engine along with it, even if you only need a small part of it. Also, python (and any other scripting language interpreter such as Perl and Ruby) is still written in C.

We’re going to explore some more scripting languages in the rest of this series. Hang onto your hat, because along with the popular languages like Python, we’re going to check out some very weird corners of programming!


Related Posts:


One Response to “The Python Programming Language”

  1. Paddy3118 Says:

    Hi,
    Your long example appeaared without any indentation! i have the same problem in Blogger, where I have taken to editing y Python progs. in the gvim editor, turning on syntax highlighting, then eporting the highlighted text as HTML that preserves the indentation.
    – Paddy.

Leave a Reply