Learning Other Languages

When you study anything new, you should be thinking about what you are doing. If you learn how to use a new tool, like a table saw, there are many concepts you need to understand before you can really master that tool (like, keeping all of your fingers attached!) If you learn those concepts well, when you get another new tool, like a radial-arm saw, you can take the concepts and adapt them to the new tool quickly. You do not need to unlearn anything, and many of the things you need to learn are just sitting there in a new form. All you need to do is answer the basic question: How do I do this thing I already know how to do with this new tool?

The same thing applies to programming a computer. There are many different kinds of computers in the world, and there are many different kinds of programming languages as well. If you understand how computers work, and what the basic concepts of the programming languages are, then moving from one language to another is pretty easy.

Let’s see. In the last five years, how many different programming languages have I used?

  • C/C++
  • Python
  • Perl
  • SQL
  • Intel/AMD Assembly Language
  • Microchip PIC microcontroller assembly language
  • Haskel
  • ML
  • Lisp
  • Ruby
  • PC Batch
  • Bash Shell
  • Visual Basic (ugh!)
  • Java
  • JavaScript
  • PHP
  • XML
  • SVG

There are surely more that I cannot remember now. No wonder I have so many books.

I do not claim to be proficient in all of those languages at any moment, I need a bit of time to come back up to speed with those I do not use on a daily basis. But, I can sit down and read a program written in any of these languages and figure out what is going on well enough to understand the program logic, and translate the ideas into the language I need to use for my current project. When you can do this, you are ready to call yourself a serious programmer! (I probably am such a beast - I have been doing this since 1965 - yikes!)

Here is a link to a review of several languages available for teaching programming that I received recently. It ends up recommending a language that is my current favorite - Python:

Introducing Python

What is Python (other than the obvious slithery answer!)

Python is a full-fledged object-oriented programming language that happens to fall into the class of languages called scripting languages. In most folk’s minds, a script is a short program designed to be used on a computer to accomplish some simple task. System administrators are always building such scripts to automate part of their jobs in keeping computers and users happy.

A scripting language gives up the idea of raw speed by giving up the compiling process in favor of interpreting a script. That usually means that some program reads the script and figures out what it wants to do and just does it without translating the script into machine language. This interpretation process is slow, but the script can be fast enough to be usable without worrying about speed.

When you develop a script, you fire up an editor, write code, save it and run it. Easy and quick.

Some scripting languages (like Python) go one step further. They take the script and break it down into a simpler form called a byte stream and then use that stream to process the program. The byte stream is not machine language, but is a special kind of computer language designed to be easy to process, and it saves time breaking up the original script into basic parts each time the script is run. This gives us back a bit of the speed without noticeably delaying our work.

Python provides all the basic features we have learned in this class, plus a few that are new! It also provides a large library of supporting functionality that makes writing programs a lot of fun. We will look at an example of building a Python program to show you how it goes. A Simple Python Program

How short can we get? Here is our Hello, World! program:

print "Hello, World!"

Short and sweet! No setup, no magic structure to learn - just simple code! Well, this will work fine, but a better version might look like this:

#! c:/tools/Python26/python.exe

print "Hello, World!"

The first line is special - especially on Linux systems. Formally, it is a comment (beginning with a sharp character). But the #! notation (called she-bang for some reason) tells the operating system what program to run to process this script. On Windows boxes, we can associate the file name extension .py with the right program, so this is not really necessary here.

Running the program

Well, we cannot go anywhere until we have Python installed on our systems. Since it is free (yeah!) - all we need to do is go to the Python website and download a copy:

Hello, World!

What more would you expect?

Notice how fast we got this running. I normally do not close my editor when I write Python programs. I just click on the Save button, then click into an open Command Prompt window and run the script.

How about something different?

Included in the Python distribution is a whole set of tools that help you write programs that work on the web. We can even set up a simple web server that will run on our local machines, even if we are not attached to the Internet. Here is what such a program looks like:

Save this as webserver.py

#! c:/tools/Python26/python.exe

import SimpleHTTPServer, BaseHTTPServer, webbrowser

# write out a basic web page
fout = open('index.html','w')
fout.write('<html><body><h1>Hello, World!</h1></body></html>')

# define a funtion to start a web server on the local machine
def run_server(server_class,handler_class):
    server_address = ('localhost',8080)
    httpd = server_class(server_address, handler_class)

# say hello to the folks!

print "Serving Web pages from localhost on port 8080!"
print "  point a browser at 'http://localhost:8080'"

# now, fire up a browser (IE takes a while to start)
browser = webbrowser.get()
url = 'http://localhost:8080'

# finally start the web server - hope it starts before the browser!
sc = BaseHTTPServer.HTTPServer
hc = SimpleHTTPServer.SimpleHTTPRequestHandler

Here is what you see if you run this program:

Serving Web pages from localhost on port 8080!
    point a browser at 'http://localhost:8080' - - [12/Dec/2006 11:33:40] "GET / HTTP/1.0" 200 -

You will need to press Ctrl-Break, or kill the command prompt window to stop the server.

What does all this stuff do?

If you look at the code, you can see what each section is up to. You should be able to follow along based on what you learned in this class. However, something will strike you right away!

Where are all the curly braces?

Python uses indentation to control structure - just like we told you you should be doing when you write C++! You must indent correctly in Python or it will not work!

Functions are created by starting off with the def keyword. When you get to the end of the prototype, you use a colon and then indent the body of the function. No more curly braces.

Notice that we have code hanging out in the breeze, as it were. As the Python processor reads your script, it simply records the functions you define, and runs the statements it finds as it reads your file. So, once we have defined a function, we can use it.

The import lines set up a connection between this file and other files containing Classes provided with the system. In our web server example, we are bringing in a class that knows how to listen for network traffic (web traffic that is) and another class that knows how to process a web request. We have also brought in a class that knows how to fire off the standard web browser on your system. This is kind of fun!

Running this short script starts off a browser and servers up one local page that it created as it ran. Can we do a bit better?

Cleaning up the code

The above example is fine, but a bit ugly. Let’s rearrange it so it is presented better:

Save this code as MyPersonalSpace.py

#! c:/tools/Python26/python.exe

import SimpleHTTPServer, BaseHTTPServer
import webbrowser

def create_index():
    fout = open('index.html','w')
    fout.write('<html><body><h1>Hello, World!</h1></body></html>')

def run_server():
    sc = BaseHTTPServer.HTTPServer
    hc = SimpleHTTPServer.SimpleHTTPRequestHandler
    server_address = ('localhost',8080)
    httpd = sc(server_address, hc)

def run_browser():
    browser = webbrowser.get()
    url = 'http://localhost:8080'

def main():
    print "Serving Web pages from localhost on port 8080!"

Now, everything is in functions and we can see what is going on a bit more clearly.

Python Basics

Python does not require that you declare variables and use data types, they are there, but you do not need to worry about all of that. You just pick a name and assign a value to it. We do have a few interesting data types to play with, though:

  • Integers
  • Floating point types
  • Strings and characters (use either quote you like)
  • Arrays (Lists)
  • Dictionaries

What is that last one?

A dictionary is just a normal array, but one that is indexed using strings instead of numbers - cool!

We can set up an empty dictionary by creating a variable and assigning it an empty dictionary ([]). Once we have set that up, we can add entries just by creating a new index string and assigning a value to that index.

mydict = {}
mydict['index'] = 'Hello World'
print mydict['index']

Python Statements

Since Python uses indentation to control structure, we have a few changes in our basic structured statements. Here are a few examples:

mydata = 5

if mydata > 3:
    print "Hello"
    print "Goodbye"

while mydata > 5:
    print "count down"
    mydata -= 1

for mydata in range(0,5):
    print mydata

That last one is a bit confusing. The range is from the first value, up to but not including the last value! So the for loop runs with values from 0 to 4. Don’t ask me why - that is just the way it is!

Obviously, there is much more to the language, this is just to let you see what it looks like, not to learn the real language. For that you can go here:

Jazzing up our page

Well, we have a web server and a web page, but, the index page is boring!

I want to know what the weather is like now! Here is a modified version that will tell me!

#! c:/tools/Python26/python.exe

import SimpleHTTPServer, BaseHTTPServer
import webbrowser
import urllib
from elementtree.ElementTree import parse

def get_weather():
    URL = 'http://xml.weather.yahoo.com/forecastrss?p=%s'
    NS = 'http://xml.weather.yahoo.com/ns/rss/1.0'
    url = URL % '78701'
    data = urllib.urlopen(url)
    rss = parse(data).getroot()
    forecasts = []
    for element in rss.findall('channel/item/{%s}forecast' % NS):
            'date': element.get('date'),
    ycondition = rss.find('channel/item/{%s}condition' % NS)
    return {
        'current_condition': ycondition.get('text'),
        'current_temp': ycondition.get('temp'),
        'forecasts': forecasts,
        'title': rss.findtext('channel/title')

def create_index():
    fout = open('index.html','w')
    weather = get_weather()
    current_cond = weather['current_condition']
    current_temp = weather['current_temp']
    forecasts = weather['forecasts']

    text = ''
    text += '<h2>Austin Weather:</h2>'
    text += '<h3>Currently: %s</h3>' % current_cond
    text += '<h3>Temperature: %s</h3>' % current_temp
    text += '<h3>Forecast:</h3>'
    text += '<table border="1"><tbody>'
    text += '<tr><td><b>Date</b></td><td><b>High</b></td>'
    text += '<td><b>Low</b></td><td><b>Conditions</b></td></tr>'

    for fc in forecasts:
        date = fc['date']
        high = fc['high']
        low = fc['low']
        cond = fc['condition']
        text += '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>' % \
            (date, high, low, cond)
    text += '</tbody></table>'
    text += '<br />When you are ready to study, click on this '
    text += '<a href="http://www.austincc.edu/rblack/classes/2009/Fall/COSC1315_005/">link!</a>'
    fout.write('<html><body><h1>My Personal Webspace!</h1>')

def run_server():
    sc = BaseHTTPServer.HTTPServer
    hc = SimpleHTTPServer.SimpleHTTPRequestHandler
    server_address = ('localhost',8080)
    httpd = sc(server_address, hc)

def run_browser():
    browser = webbrowser.get()
    url = 'http://localhost:8080'

def main():
    print "Serving Web pages from localhost on port 8080!"



If you try to run this code yourself, you will need to add the ElementTree library to your system. Copy the script from this link onto your system and run it:

Then do the following:

easy_install elementtree

Here is what I got:


Phew! I added a new routine that uses a web service to fetch the current weather from yahoo.com. This is a neat way to get information into your program as long as you have a working Internet connection when you run the program (and who does not these days?)

The weather comes back in the form of an XML page of text, not something I can use. But, Python comes with another tool that can read such a page and strip off stuff I am interested in. So, I parse the page and get my weather data stored in a special kind of array called Or, we can assign a whole bunch

Finally, I added a bunch of lines to create HTML code to display the forecast in a table. Another language to learn! All in all, this is still ugly, but useful! And, it shows the kind of things you can do if you really want to explore where programming can take you!

Hope you enjoyed the course, and that you learned a bit! Have fun!