- •Introduction
- •Introduction - What, Why, Who etc.
- •Why am I writing this?
- •What will I cover
- •Who should read it?
- •Why Python?
- •Other resources
- •Concepts
- •What do I need?
- •Generally
- •Python
- •QBASIC
- •What is Programming?
- •Back to BASICs
- •Let me say that again
- •A little history
- •The common features of all programs
- •Let's clear up some terminology
- •The structure of a program
- •Batch programs
- •Event driven programs
- •Getting Started
- •A word about error messages
- •The Basics
- •Simple Sequences
- •>>> print 'Hello there!'
- •>>>print 6 + 5
- •>>>print 'The total is: ', 23+45
- •>>>import sys
- •>>>sys.exit()
- •Using Tcl
- •And BASIC too...
- •The Raw Materials
- •Introduction
- •Data
- •Variables
- •Primitive Data Types
- •Character Strings
- •String Operators
- •String operators
- •BASIC String Variables
- •Tcl Strings
- •Integers
- •Arithmetic Operators
- •Arithmetic and Bitwise Operators
- •BASIC Integers
- •Tcl Numbers
- •Real Numbers
- •Complex or Imaginary Numbers
- •Boolean Values - True and False
- •Boolean (or Logical) Operators
- •Collections
- •Python Collections
- •List
- •List operations
- •Tcl Lists
- •Tuple
- •Dictionary or Hash
- •Other Collection Types
- •Array or Vector
- •Stack
- •Queue
- •Files
- •Dates and Times
- •Complex/User Defined
- •Accessing Complex Types
- •User Defined Operators
- •Python Specific Operators
- •More information on the Address example
- •More Sequences and Other Things
- •The joy of being IDLE
- •A quick comment
- •Sequences using variables
- •Order matters
- •A Multiplication Table
- •Looping - Or the art of repeating oneself!
- •FOR Loops
- •Here's the same loop in BASIC:
- •WHILE Loops
- •More Flexible Loops
- •Looping the loop
- •Other loops
- •Coding Style
- •Comments
- •Version history information
- •Commenting out redundant code
- •Documentation strings
- •Indentation
- •Variable Names
- •Modular Programming
- •Conversing with the user
- •>>> print raw_input("Type something: ")
- •BASIC INPUT
- •Reading input in Tcl
- •A word about stdin and stdout
- •Command Line Parameters
- •Tcl's Command line
- •And BASIC
- •Decisions, Decisions
- •The if statement
- •Boolean Expressions
- •Tcl branches
- •Case statements
- •Modular Programming
- •What's a Module?
- •Using Functions
- •BASIC: MID$(str$,n,m)
- •BASIC: ENVIRON$(str$)
- •Tcl: llength L
- •Python: pow(x,y)
- •Python: dir(m)
- •Using Modules
- •Other modules and what they contain
- •Tcl Functions
- •A Word of Caution
- •Creating our own modules
- •Python Modules
- •Modules in BASIC and Tcl
- •Handling Files and Text
- •Files - Input and Output
- •Counting Words
- •BASIC and Tcl
- •BASIC Version
- •Tcl Version
- •Handling Errors
- •The Traditional Way
- •The Exceptional Way
- •Generating Errors
- •Tcl's Error Mechanism
- •BASIC Error Handling
- •Advanced Topics
- •Recursion
- •Note: This is a fairly advanced topic and for most applications you don't need to know anything about it. Occasionally, it is so useful that it is invaluable, so I present it here for your study. Just don't panic if it doesn't make sense stright away.
- •What is it?
- •Recursing over lists
- •Object Oriented Programming
- •What is it?
- •Data and Function - together
- •Defining Classes
- •Using Classes
- •Same thing, Different thing
- •Inheritance
- •The BankAccount class
- •The InterestAccount class
- •The ChargingAccount class
- •Testing our system
- •Namespaces
- •Introduction
- •Python's approach
- •And BASIC too
- •Event Driven Programming
- •Simulating an Event Loop
- •A GUI program
- •GUI Programming with Tkinter
- •GUI principles
- •A Tour of Some Common Widgets
- •>>> F = Frame(top)
- •>>>F.pack()
- •>>>lHello = Label(F, text="Hello world")
- •>>>lHello.pack()
- •>>> lHello.configure(text="Goodbye")
- •>>> lHello['text'] = "Hello again"
- •>>> F.master.title("Hello")
- •>>> bQuit = Button(F, text="Quit", command=F.quit)
- •>>>bQuit.pack()
- •>>>top.mainloop()
- •Exploring Layout
- •Controlling Appearance using Frames and the Packer
- •Adding more widgets
- •Binding events - from widgets to code
- •A Short Message
- •The Tcl view
- •Wrapping Applications as Objects
- •An alternative - wxPython
- •Functional Programming
- •What is Functional Programming?
- •How does Python do it?
- •map(aFunction, aSequence)
- •filter(aFunction, aSequence)
- •reduce(aFunction, aSequence)
- •lambda
- •Other constructs
- •Short Circuit evaluation
- •Conclusions
- •Other resources
- •Conclusions
- •A Case Study
- •Counting lines, words and characters
- •Counting sentences instead of lines
- •Turning it into a module
- •getCharGroups()
- •getPunctuation()
- •The final grammar module
- •Classes and objects
- •Text Document
- •HTML Document
- •Adding a GUI
- •Refactoring the Document Class
- •Designing a GUI
- •References
- •Books to read
- •Python
- •BASIC
- •General Programming
- •Object Oriented Programming
- •Other books worth reading are:
- •Web sites to visit
- •Languages
- •Python
- •BASIC
- •Other languages of interest
- •Programming in General
- •Object Oriented Programming
- •Projects to try
- •Topics for further study
Collections
Computer science has built a whole discipline around studying collections and their various behaviours. Sometimes collections are called containers. In this section we will look first of all at the collections supported in Python then we’ll conclude with a brief summary of some other collection types you might come across in other languages.
Python Collections
List
A list is a sequence of items. What makes it different from an array is that it can keep on growing - you just add another item. But it's not usually indexed so you have to find the item you need by stepping through the list from front to back checking each item to see if it's the item you want. Both Python and Tcl have lists built into the language. In BASIC it's harder and we have to do some tricky programming to simulate them. BASIC programmers usually just create very big arrays instead. Python also allows you to index it's lists. As we will see this is a very useful feature.
List operations
Python provides many operations on collections. Nearly all of them apply to Lists and a subset apply to other collection types, including strings which are just a special type of list of characters. To create and access a list in Python we use square brackets. You can create an empty list by using a pair of square brackets with nothing inside, or create a list with contents by separating the values with commas inside the brackets:
>>>aList = []
>>>another = [1,2,3]
>>>print another [1, 2, 3]
We can access the individual elements using an index number, where the first element is 0, inside square brackets:
>>> print another[2] 3
We can also change the values of the elements of a list in a similar fashion:
>>>another[2] = 7
>>>print another [1, 2, 7]
You can use negative index numbers to access members from the end of the list. This is most commonly done using -1 to get the last item:
>>> print another[-1] 7
We can also add new elements to the end of a list using the append() operator:
>>>aList.append(42)
>>>print aList [42]
We can even hold one list inside another, thus if we append our second list to the first:
>>> aList.append(another)
26
>>> print aList [42, [1, 2, 7]]
Notice how the result is a list of two elements but the second element is itself a list (as shown by the []’s around it). This is useful since it allows us to build up representations of tables or grids using a list of lists. We can then access the element 7 by using a double index:
>>> print aList[1][2] 7
The first index, 1, extracts the second element which is in turn a list. The second index, 2, extracts the third element of the sublist.
The opposite of adding elements is, of course, removing them and to do that we use the del command:
>>>del aList[1]
>>>print aList [42]
If we want to join two lists together to make one we can use the same concatenation operator ‘+’ that we saw for strings:
>>>newList = aList + another
>>>print newList
[42, 1, 2, 7]
In the same way we can apply the repetition operator to populate a list with multiples of the same value:
>>>zeroList = [0] * 5
>>>print zeroList [0, 0, 0, 0, 0]
Finally, we can determine the length of a list using the built-in len() function:
>>>print len(aList)
2
>>>print len(zeroList)
5
Tcl Lists
Tcl also has a built in list type and a variety of commands for operating on these lists. These commands are identifiable by the 'l' prefix, for example linsert,lappend, lindex, etc. An example of creating a simple Tcl list and accessing a member follows:
%set L [list 1 2 3]
%put [lindex $L 2]
3
27
Tuple
Not every language provides a tuple construct but in those that do it’s extremely useful. A tuple is really just an arbitrary collection of values which can be treated as a unit. In many ways a tuple is like a list, but with the significant difference that tuples are immutable which is to say that you can’t change them nor append to them once created. In Python, tuples are simply represented by parentheses containing a comma separated list of values, like so:
>>> aTuple = (1,3,5)
>>> print aTuple[1] # use indexing like a list 3
>> aTuple[2] = 7 # error, can’t change a tuple’s elements Traceback (innermost last):
File "", line 1, in ? aTuple[2] = 7
TypeError: object doesn't support item assignment
The main things to remember are that while parentheses are used to define the tuple, square brackets are used to index it and you can’t change a tuple once its created. Otherwise most of the list operations also apply to tuples.
Dictionary or Hash
A dictionary as the name suggests contains a value associated with some key, in the same way that a literal dictionary associates a meaning with a word. The value can be retrieved by ‘indexing’ the dictionary with the key. Unlike a literal dictionary the key doesn’t need to be a character string(although it often is) but can be any immutable type including numbers and tuples. Similarly the values associated with the keys can be any kind of Python data type. Dictionaries are usually implemented internally using an advanced programming technique known as a hash table. For that reason a dictionary may sometimes be referred to as a hash. This has nothing to do with drugs!
Because access to the dictionary values is via the key you can only put in elements with unique keys. Dictionaries are immensely useful structures and are provided as a built-in type in Python although in many other languages you need to use a module or even build your own. We can use dictionaries in lots of ways and we'll see plenty examples later, but for now, here's how to create a dictionary in Python, fill it with some entries and read them back:
>>>dict = {}
>>>dict['boolean'] = "A value which is either true or false"
>>>dict['integer'] = "A whole number"
>>>print dict['boolean']
A value which is either true or false
Notice that we initialise the dictionary with braces, then use square brackets to assign and read the values.
Due to their internal structure dictionaries do not support very many of the collection operators that we’ve seen so far. None of the concatenation, repetition or appending operations work. To assist us in accessing the dictionary keys there is a function that we can use, keys(), which returns a list of all the keys in a dictionary.
If you're getting a bit fed up, you can jump to the next chapter at this point. Remember to come back and finish this one when you start to come across types of data we haven't mentioned so far.
28
