Two days of demonstration scripts in Python
Archive - Originally posted on "The Horse's Mouth" - 2009-09-05 08:25:36 - Graham EllisI've spent the last two days introducing Python to a group of nine delegates (and, naturally, enjoying doing so). As I usually do, I have wrote a lot of new examples to show not only how the language and programs work, but also the thought process behind writing them. At the delegate's request, I have added the examples onto our web site --- linkable by the delegates (and anyone else who cares to take a look) from the following list:
EARLY DEMONSTRATIONS
early python demonstration - using, re-using, copying variables
first real application - simple calculation
FUNCTIONS, FROMs and IMPORTS
A file of functions for 'from' or 'import'
file to be included to bring in application globals
loading application globals
How EVERYTHING is an object - even functions!
Hiding algorithms in functions - 'encapsulation'
Using a generator to avoid a large intermediate list - control
lists of functions, lambdas, callbacks (posh/flexible ways to use functions)
Generator function to prevent need for intermediate list
LISTS
ways of looping through a list
Some early list demonstrations!
Lists, lists of lists, mutable and immutable
generatings lists of 365 elements to convert day of year to month and day
Use of xrange rather than range to avoid huge intermediate lists
Trying to modify a tuple
FILES and OTHER DATA INPUT / OUTPUT
A one-liner to print a file's contents
File read and write - program 'samples' every 10th line of a log file
Reading a file line by line (good for huge files)
Reading a web page 'as if it was a local file'
Running an operating system command via a pipe
STRINGS and REGULAR EXPRESSIONS
Some examples of the % (string formatting) operator
Regular Expression to extract data from log file (and dictionary analyse)
OBJECTS
First steps in Object definition and use
Sample class with test harness too
Converting a file on disc to a list of objects in memory
I will add some notes, based on comments received about some of my examples recently. These are little demonstration programs. I would use standards such as a variable naming standard in 'live' programs - to avoid confusion about spelling and what variables do later. I would comment my programs far better. I would include documentation strings. I would validate user input .... I talk about such things at great length on ALL courses because they are vital! but in some of these early examples, they would extend the course running time and pad out the source code so that it was hard to find the real nubbs!
OK ... If you want to learn Python / see me set up things like this and fully understand the examples, the course you need is Learning to program in Python if you have never programmed before, or Python Programming if you are converting from C, C++ or some other language