SCOUG Logo


Next Meeting: Sat, TBD
Meeting Directions


Be a Member
Join SCOUG

Navigation:


Help with Searching

20 Most Recent Documents
Search Archives
Index by date, title, author, category.


Features:

Mr. Know-It-All
Ink
Download!










SCOUG:

Home

Email Lists

SIGs (Internet, General Interest, Programming, Network, more..)

Online Chats

Business

Past Presentations

Credits

Submissions

Contact SCOUG

Copyright SCOUG



warp expowest
Pictures from Sept. 1999

The views expressed in articles on this site are those of their authors.

warptech
SCOUG was there!


Copyright 1998-2024, Southern California OS/2 User Group. ALL RIGHTS RESERVED.

SCOUG, Warp Expo West, and Warpfest are trademarks of the Southern California OS/2 User Group. OS/2, Workplace Shell, and IBM are registered trademarks of International Business Machines Corporation. All other trademarks remain the property of their respective owners.

The Southern California OS/2 User Group
USA

SCOUG-Programming Mailing List Archives

Return to [ 13 | January | 2005 ]


Date: Thu, 13 Jan 2005 15:13:55 PST8
From: Sheridan George <s-geo@usa.net >
Reply-To: scoug-programming@scoug.com
To: scoug-programming <scoug-programming@scoug.com >
Subject: SCOUG-Programming: First Draft of Python Presentation

Content Type: text/plain

Here is an unfinished draft of what I'm proposing for my part of the presentation. My intent is to
show at least enough Python constructs for Greg's presentation to make sense. I'm not yet done and
my concern is it is getting too long. Is it too detailed?

(The presentation is in HTML which doesn't translate in e-mail when I have HTML turned off.)

Sheridan

A Short Introduction to Python

The intent of this introduction is to allow a non-programmer to start using Python and get some
quick and dirty but meaningful scripting done. It by no means is a real tutorial on the language.
It simply covers:

* output,
* variable
* assignment,
* keyboard input,
* comment,
* data types, and
* a few program flow constructs.

The ability to start the Python interpreter is assumed.
What is Python?

Python is an interpreted, interactive, object-oriented programming language. It is often compared to
Tcl, Perl, Scheme or Java.

Python combines remarkable power with very clear syntax. It has modules, classes, exceptions, very
high level dynamic data types, and dynamic typing. There are interfaces to many system calls and
libraries, as well as to various windowing systems (X11, Motif, Tk, Mac, MFC). New built-in modules
are easily written in C or C++. Python is also usable as an extension language for applications that
need a programmable interface.

The Python implementation is portable: it runs on many brands of UNIX, on Windows, OS/2, Mac, Amiga,
and many other platforms. If your favorite system isn't listed here, it may still be supported, if
there's a C compiler for it. Ask around on news:comp.lang.python -- or just try compiling Python
yourself.

The Python implementation is copyrighted but freely usable and distributable, even for commercial
use. (Python.org)
What kind of a language is Python?
Python is a programming language that appears to be interpreted (no separate compilation step), is
semi-compiled (internally it has a JIT compiler that compiles to a byte-code) and runs in a virtual
machine, and it permits programs to be procedural or object orientated.

According to David Mertz Python is "an imperative programming language, rather than declarative
(functional or logical) one. Python is dynamically and strongly typed with late binding."

Python fits into the set of languages that limit visibility (scope) of variables. In Python this
visibility is called Namespace. A Python program can be viewed as a hierarchy of namespaces. (For
the curious, this is done using Python's dictionary object. More on dictionaries later.)
Simple Python constructs
The first constructs we will discuss are print and assignment.

* The command print, which displays information on the computer screen, has the form:
o print 17
o print "aString"
o and print abc
* Note: the command print is all lower case or Python will not print. In fact, Python will
complain; unless the program contains a variable named Print.
* variable is a name that is a reference to a memory location
o must start with an alpha character
o are not declared
o can be bound and rebound to different types at will - usually via an assignment
o must be bound, even if to an empty object, before being referred to (read used - other
than in an assignment)
* An assignment "loads" a variable with some object. An assignment has the form:
o x = 17
o abc = "aString"
o x = abc
o a,b = 5, "a"

Running the text examples in the interpreter results in:


>>>
>>>x = 17

>>>x

17
>>>abc = "aString"
>>> print abc
aString
>>> x = abc
>>> print x
aString
>>> a, b = 5, "a"

>>> print a
5
>>> print b
a

# the chevron is the sign that the Python interpreter is waiting for input
# the identifier (name) x (a variable in global namespace) is bound to (associated with) the
integer/constant object 17
# shorthand for 'print x' which causes the object bound to (think contents of) the variable to
display itself
# the object (contents of variable [container if you will] x) is displayed
# identifier abc (in global namespace) is is bound to (associated with) the string object aString
# display the contents of variable abc; actually the object bound to var abc displays itself
# the object is displayed
# variable x is bound to the contents of variable abc ...

# ... which is demonstrated here
# ordered assignment: order is maintained between the left side variables and the right side objects

# the contents of variable a

# the contents of variable b

Technically, the variables don't contain the value (object). The value is bound to the variable in
the current name space. For example:


>>> def hello():
... pass
...
>>> hello.x = 55
>>> print x, hello.x
aString 55
>>> hello.j = 77
>>> print j
Traceback (most recent call last):
File "", line 1, in ?
NameError: name 'j' is not defined
>>> print hello.j
77
# create a namespace called hello
# Python's NOP command

# create variable named x in hello namespace and bind it to the number object 55
# display global namespace variable x and hello namespace variable x
# aString is from the earlier example as long as the interpreter has not been restarted
# create variable named j in hello namespace and bind it to the number object 77
# display variable j in global namespace
# Python complains that there is no such thing

# display variable j in hello namespace
# there it is

Program comments are vital to explaining different parts of a program. A comment is simply:
# A pound sign followed by alphanumerics and ended by a 'newline' (carriage return).

The last of the simple constructs is used to get data into the program from the keyboard. The form
is: var = raw_input("a prompt to be displayed so the user
knows what to input").


>>> UserName = raw_input("Type in your name ")
Type in your name Sheridan George
>>> print UserName
Sheridan George
# get the name of the user
# the prompt is displayed and the operator types in their name

# see, it really is in the computer

Data Types
Python, as a strongly typed language, has many built-in data types which are objects. Bring an
object means the type has "skills". These skills are what the object can do such as:

* print itself
* compare itself to another object (of similar type)
* add/concatenate similar objects together
* and many others

Objects have attributes, also. Attributes are characteristics that make that object special. Some
attributes are:

* has a value
* can be changed (mutable),
* can not be changed (immutable)
* and others

Note: not all objects have the same attributes. That is what makes them unique.

The main types are:

* Numbers
o integer (limited in size by the platform -- usually -232 to 232- 1)
o integer Long (limited in size to memory on most platforms)
o are immutable (arithmetic operations create a new object)
o can be: decimal, octal, hexadecimal, and complex
* Sequences
o a sequence is an ordered (not necessary sequential) container of items that is indexable
o Lists
+ a mutable ordered sequence of comma separated items of similar or disparate types
+ indexable and sliceable
+ denoted by brackets;
aList = ["dog", cat, 12345]
print aList, type(aList)
['dog', 999, 12345]

o Strings
+ ordered collection of characters (a single character is a string of length 1)
+ immutable -- string operations create new strings
+ quoted or triple-quoted
# quoted by pairs of double quotes (") or pairs of single quotes (')
# triple-quoted (pairs of """) allow strings to span multiple lines and to
maintain format
"""
This is a line that has funky spacing with a bunch of
holes in it.
"""
+ raw string
# same as a quoted or triple-quoted string but with an R in front of the quote
# the string is reproduced as is even if it contains escaped characters,
which are not translated but kept intact
# useful is the string contains many backslashes
o Tuples
+ similar to a list except:
# it can contain any combination of any type
# it is immutable
# tuples may be nested (a tuple may contain (a) tuple(s))
# tuples are formed by separating a series of objects with commas, optionally
inside parentheses:
x=4,5,"gent"
print x, type(x)
((4, 5, 'gent'), )
* Dictionary
o A mapping (arbitrary collection of indexed objects) type that mutable and unordered
o A dictionary consists of a key and its associated value. Its form is: {key1: value1,
key2: value2, ..., keyN: valueN} (For the curious, the idea of a dictionary is based on a language
dictionary where the key is the word one wants to look up and the value is/are the definition(s) for
that word.
o dictionaries are created by curly braces ({})
o keys must be immutable and hashable but may be of different types
o values may be any type even other dictionaries
<>dict = {1:"aNum", "bat": 12, "colors":("green", "brown")}
print dict, type(dict)
{1: 'aNum', 'bat': 12, 'colors': ('green', 'brown')}
* None
o None (capitalized contrary to normal Python convention) is Python's NULL value.
o Functions that are not coded to return a specific value return None
* Boolean
o There is no explicit boolean type in Python. However, every data value can be
evaluated as true or false. Any zero value, the reserved word None, or an empty string, tuple,
list, or dictionary will evaluate as false; otherwise as true.
o Python versions above 2.2.0 have the reserved words True and False (capitalized) to
represent true and false.

Less Simple Constructs
Above we discussed the simple print statement. Let me introduce you to another form of print - the
formatted print. Its form is: print "Display a number, %d, then a string, %s, and even variables,
%s, %f") % (5, "aString", var1, var2).


>>> var1 = "Words"
>>> var2 = 3.14159
>>> print ("Display a number, %d, then a string, %s, and even variables, %s, %f")\
% (5, "aString", var1, var2)
Display a number, 5, then a string, aString, and even variables, Words, 3.141590
# name var1 bound to the string Words
# name var2 bound to the number Pi
# the print statement with a ...
# ... continuation symbol (\)
# the display

The % symbol is a placeholder and the letter after it described what type a datum must be to replace
it. The 'd' allows integer digits (type int); the 's' allows any string (alphanumerics - type str);
the 'f' allows floating point numbers (type float). There are other placeholder combinations.
Substitutions for the placeholders are in the order of the placeholders. This is called positional
notation.

It is easy to see that an involved formatted print statement could get unwieldy. A relatively
simple, but ugly, example is one that prints a list of any 20 integers:
print ("The first ten integers are: %d, %d, %d, %d, %d, %d, %d, %d, %d, %d") % (i1, i2, i3, i4, i5,
i6, i7, i8, i9, i10)
print (" and the next ten are: %d, %d, %d, %d, %d, %d, %d, %d, %d, %d") % (i11, i12, i13,
i14, i15, i16, i17, i18, i19, i20)

where names (variables) i1 through i20 bound to integers of some kind.

There is a way to do this with less typing and more clarity - use a triple-quoted and a dictionary.

It turns out that the triple-quoted string can be used in a print command. We can print our 20
integers thusly:
print ("""
The first ten integers are: %d, %d, %d, %d, %d, %d, %d, %d, %d, %d,
and the next ten are: %d, %d, %d, %d, %d, %d, %d, %d, %d, %d"""")\
% (i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11, i12, i13, i14, i15, i16, i17, i18, i19, i20)


We still have the complication of a long list of placeholders and an equally long list of
replacement values. That list of replacement values (but not placeholders) can be shortened by
using a dictionary.

A dictionary is one cool item. recall it is a construct that consists of a key and its associated
value.

The keys must be an immutable data type (string, tuple, and others). A key's associated value may
be any data type including another dictionary.

The result of all of this is our print statement is now:
print ("""
The first ten integers are: %('k1')d, %('k2')d, %('k3')d, %('k4')d, %('k5')d, %('k6')d, %('k7')d,
%('k8')d, %('k9')d, %('k10')d,
and the next ten are: %('k11')d, %('k12')d, %('k13')d, %('k14')d, %('k15')d, %('k16')d,
%('k17')d, %('k18')d, %('k19')d, %('k20')d
"""") % dict

where dictionary dict holds the 20 integer data and 'k1' -' k20' are the keys in dict. In this
example the loading of dict is not shown to keep the print statement clear. We'll tackle that
problem later. Suffice it to say, if loading the dictionary is messy (meaning it can't be done
programmatically) this technique may not be worth using.

Because each dictionary key must be explicitly called out (named notation) in the print statement,
there still has to be as many placeholders as there are items to be replaced. But explicit naming
means the order of the keys in the dictionary (which by definition is random) is of no concern. It
also means that 'k1' - 'k20' can be in any order in the placeholder string. This open up other
possibilities for the display.

For example, we could, assuming the integers are in sequential order, print the 10 odd integers on
one line and the evens on another:

print ("""
The first ten integers are: %('k1')d, %('k3')d, %('k5')d, %('k7')d, %('k9')d, %('k11')d, %('k13')d,
%('k15')d, %('k17')d, %('k19')d,
and the next ten are: %('k2')d, %('k4')d, %('k6')d, %('k8')d, %('k10')d, %('k12')d, %('k14')d,
%('k16')d, %('k18')d, %('k20')d
"""") % dict


Before we can show other running examples we need to cover one other command: import

Python, like many languages, has a core set of data types and operations. Added to that are modules
of functionality or libraries of modules of all kinds; some built by the folks at python.org and
others by third parties. One of the standard modules is math. The random number generator we need
for DictBasedRandomPhoneBook.py program is in math. We'll discuss import then the Phone Book script.

To be completed.

=====================================================

To unsubscribe from this list, send an email message
to "steward@scoug.com". In the body of the message,
put the command "unsubscribe scoug-programming".

For problems, contact the list owner at
"rollin@scoug.com".

=====================================================


Return to [ 13 | January | 2005 ]



The Southern California OS/2 User Group
P.O. Box 26904
Santa Ana, CA 92799-6904, USA

Copyright 2001 the Southern California OS/2 User Group. ALL RIGHTS RESERVED.

SCOUG, Warp Expo West, and Warpfest are trademarks of the Southern California OS/2 User Group. OS/2, Workplace Shell, and IBM are registered trademarks of International Business Machines Corporation. All other trademarks remain the property of their respective owners.