Friday, January 27, 2012

Tutoriality I

Time for a tutorial.  Let's try AstroPython's "Getting started with Python in astronomy."  That sounds superfriendly and relevant.

Hmm, its first recommendation is Dive Into Python.  Here's the book as a PDF, zipped.  Skipping chapter 1 b/c my sysadmin told me what to install.  Skipping Chapter 2 b/c it's terrifying and opaque.  On to Chapter 3.  Things I learn:
1) A dictionary in Python is like a hash in Perl.  OK.  Worth knowing for later.

2) Lists in python work a lot like arrays in perl:

ipython -pylab
In [8]:  foo=['a', 'b', 'c', 'd']
In [9]: foo[-1]
Out[9]: 'd'
In [10]: foo[0]
Out[10]: 'a'
And I can add lists together with the + sign, as God intended.

And search for an occurrence of a value:
In [17]: foo.index('c')
Out[17]: 2
And test boolean statements:
In [19]: "d" in foo
Out[19]: True
And strip out values:
In [20]: foo.remove('c')
In [21]: foo
Out[21]: ['a', 'b', 'd']
There's "pop", too, which is an old friend from perl.

Now this part makes no sense yet:
In [27]: li = [1, 2]
In [28]: li * 3
Out[28]: [1, 2, 1, 2, 1, 2]
The * operator acts on lists as a repeater.  OK that's weird.  But it barfs if  the operator acts on a float:  "* 3.0".  So if we're bookkeeping floats correctly, that would complain.

OK, now to Tuples.  "A tuple is an immutable list. A tuple can not be changed in any way once it is created."  Got it.  It's defined the same way as a list, except it gets round parentheses:
t = ('you', 'no', 'be', 'changing', 'my', 'tuple')
In [37]: t[3]
Out[37]: 'changing'
And since a tuple is immutable, you can't pop, append, or extend it.  Nor can you find elements via "index".  So why do I need a tuple?  OK, they're faster, and useful if you want read-only data.  And they're good as keys in dictionaries.  OK, but I don't care yet.

The Tuple function turns a list into a tuple.  The builtin List function turns a tuple into a list.  "In effect, Tuple freezes a list, and List thaws a tuple."  Got it.

Now on to variables.  Thank god, I don't need to explicitly type variables.  Like perl, it just figures out what the variable is given the value.

No comments:

Post a Comment