Introduction
Today, you will get acquainted with the Python programming language. Here is a short overview of what Python is. (Please read it.) There are a number of other free, downloadable tutorials and reference guides in the Documentation area of the Python website -- you should spend some time outside of class browsing these materials to become familiar with them, and refer back to them whenever needed.
First Explorations
Start the Python interpreter in interactive mode, preferably by
launching the IDLE development environment. Then follow along the
commands below (in bold font
), typing them into
IDLE yourself to see the results. With each step below I also include
some explanation and/or external links for you to explore.
First we start with the classic "Hello World" program. In Python, this is simply written as one line of code:
>>> print "Hello, World!"
Here are some more examples exploring the behavior of the print statement. Notice that multiple items separated by commas are printed out on the same line, separated by spaces. Alternatively, one may concatenate strings using the + operator (as in Java):
>>> print ":-)"
>>> print "Hello, World!", ':-)'
>>> print 'I said, "Hello, World!"' + '8-)'
String literals can be specified using either single or double quotes. Within a single quoted string, you do not have to escape (\"") the double quote character, and vice versa.
Python comes with several powerful, built-in data types. One of these is the list data type, which are like extensible arrays in other languages. List literals can be defined using square brackets, with items (of any type, including other lists) separated by commas:
>>> eyes = [ ':', ';', '8' ];
>>> noses = [ '', '-', '+', '<', '\'', '=' ];
>>> mouths = [ x for x in 'poO)]}({[/\\>|' ]; # list comprehension
>>> mouths += [ '()', '[]', '{}', '<>', 'X', 'x' ]
The first two lines above define lists of characters. The third
line uses a concept called "list comprehensions." The
string 'po...\\>|'
is considered a sequence of
characters. The third statement constructs a list by taking each
individual character in the string and inserting it into the list.
(This page
describes the concept of list comprehensions in Python.)
The fourth line appends additional character strings onto
the mouths
list.
There are two types of loops in Python: while loops and for loops. The for loops work differently from those in Java or C (although the new Java 'foreach' construct is quite similar). Before looking at a sample for loop, you need to understand how Python handles the bodies of loops and other compound constructs. Instead of using braces {} like Java or C, Python looks at the level of indentation to determine the grouping of statements. This means you must be careful about the indentation of your code or it won't work correctly. Here is an example of a for loop in Python:
>>> extras = []
>>> for nose in noses:
extras.append( nose + '=' )
extras.append( '=' + nose )
# you need to leave a blank line here in interactive mode
>>> noses += extras
>>> noses
The alignment in interactive mode might not be quite correct because of the extra >>> in the first line, but in a source code file, you would use the 'Tab' key to indent the middle two lines. (Many Python editors support automatic indentation.) The result of the last expression should show you what happened.
Notice that the for loop in Python iterates (loops) over a sequence (could be a list, string, or tuple) of items, temporarily assigning each item to a loop variable and then executing the body of the loop.
So far, the statements we have executed have constructed three lists: eyes, mouths, and noses. You can use the print statement to inspect the contents of each list. Now, let's try constructing a list of all possible smiley faces that could be built from combinations of the individual strings. We'll use three nested for loops:
>>> smilies = []
>>> for eye in eyes:
for mouth in mouths:
for nose in noses:
smilies.append( eye + nose + mouth )
If you were to print out smilies now, you would probably get a screen of about 1,000 different smiley faces. To determine the length of a list, use the len function:
>>> print len(smilies)
One last example before we look at a source file combining all the steps above. You may recall using formatted output with the 'printf' functions/methods in C or Java. You can build formatted strings in Python using similar syntax:
>>> print "Formatted string test: %d %5d %10s" % (1, 2, 'hello' )
print "Formatted string test: %d %3d %10s" % (1, 2, 'hello' )
See this page or this page or this page for more details of how this works.
Putting it all together
Let's now look at a complete Python program that puts together the various steps above to print out a set of all possible text smiley faces. You may download the source code here: smiley_gen.py. This example shows you how to define functions in Python (using 'def'). Notice the indentation. It also demonstrates features such as default argument values for function parameters, and supply arguments by name (see fieldWidth supplied in the call to formatFields() in the main() function). When you get to this point of the lab, you may call me over and I will go over some other important features of Python that are in this example.
More Python language features
If we have time during this lab period, I will go over another example demonstrating a variety of additional language features, including:
- Dictionaries (mappings) (thinkCSpy, ch.10)
- File input/output; exception handling (thinkCSpy, ch.11)
- More string operations
- if/elif/else construct; comparison operators (e.g. 1 < x <= 10 ); logical operators: and, or, not (thinkCSpy, ch.4)
- doc strings; multi-line strings using """ (DiveIntoPython, 2.3)
- Modules (A module is a file that contains a collection of related functions grouped together.) (DiveIntoPython, 5.2)
- Command-line arguments, using sys.argv (DiveIntoPython, 10.6)
The source code for this demonstration is here:
uncontract.py. It is a program intended to read in a text
file and replace all contractions (e.g. I'll) with their expanded
forms (e.g. I will).
The interactive session: uncontract_console.txt
and contractions.txt.
Related Links
- The Python quick reference at this page. (Also has documentation for Tkinter GUI programming in Python)