Monday, August 13, 2007

Python Intro

Gave a short talk at the Portland Cocoaheads meeting last Wednesday, Aug. 8th. I basically wanted to highlight the bits of Python that I wish I had known before I dove in. Here's the code I used to copy and paste into an interactive Python session:



#!/usr/local/bin/python

# indentation
a = 1
if (a == 1):
print a
else:
print "a != 1"

# if statement
a = 3
if a > 0:
print 'greater'
elif a == 0:
print 'equal'
else:
print 'less'

# while loops
a = 3
while a > 0:
print "a = %d"%a
a -= 1

#functions
def hello(who):
print "Hello, " + who

hello("world")

# strings
def hello(who):
return "Hello, " + who
s = hello("world")
print "s = %s"%s
print s[0:5]
print len(s[0:5])
print s.upper()

# lists
l = [ 'a', 'b', 'c', 1, 2, 3 ]
print l
# third element
print l[2]
# third, fourth, and fifth elements
print l[2:4]
# last element
print l[-1]
# append
l.append('snake')
print l

# for loops
for i in l:
print i

# dictionary
d = {'alpha': 1, 'beta':2, 'gamma':3}
d['delta'] = 4
print d
print d['gamma']
del d['gamma']
d.keys()
if d.has_key('gamma'):
print 'has gamma'
else:
print 'does not have gamma'
for k,v in d.iteritems():
print "k = ",k
print "v = ",v

# sets
s1 = set()
for x in 'aabbbccccdddddefffffff':
s1.add(x)
print 'set s1 = ',s1

# dir() function
# dir(s)

# help function
import platform
#help(platform)
platform.processor()

# using pyobjc
#
from Foundation import *
d1 = NSMutableDictionary.dictionary()
print isinstance(d, dict)
print type(d)
print isinstance(d1, dict)
print type(d1)
print isinstance(d1, NSMutableDictionary)
d1.setObject_forKey_(42, 'key2')
d1['key1'] = 'hello'
print d
print d1

# addressbook example
import AddressBook
book = AddressBook.ABAddressBook.sharedAddressBook()
b = book.people()
print "Number of people in addressboo is ",len(b)
print b[1].valueForProperty_(AddressBook.kABLastNameProperty)
print type(b)

Editors:

1 comment:

Prunella said...

You write very well.