1. Installing Python 3.2 & Mercurial :: InstallingPython
2. Python Overview
- a pretty ok tutorial :: a byte of python
- a not great tutorial: python tutorial
- strings, lists, & dictionaries
Copy this David Foster Wallace story into your interpreter
dfw = A Radically Condensed History of Postindustrial Man
Choose a word in the story; how many times does it occur?
words = dfw.split()
words.count('word')
How many words are there in the story?
len(dfw.split())
How many letters?
len(dfw)
Replace all instances of "he" with "He".
dfw.replace(' he ', ' He ')
or
nl = []
for word in dfw.split():
if word == 'he':
word = 'He'
nl.append(word)
new_dfw = ' '.join(nl)
Turn all the sentences into exclamations.
dfw.replace('.','!')
Sort each of the words from the story alphabetically.
l = dfw.split()
l.sort()
or
sorted(dfw.lower().split())
Now sort them by word length.
l.sort(key=len)
or
sorted(dfw.split(), key=len)
Write definitions for as many of the words as you can. Now go through the story and replace each word with its definition.
d = {' he ':' boy ', 'witticism':'a funny and cynical turn of phrase'}
for word, definition in d.items():
dfw = dfw.replace(word, definition)
other things that came up
- print() – writes a string to your screen documentation
>>> print('the quick brown fox jumped...')
the quick brown fox jumped...
- for, while, if documentation
>>> for i in [1,2,3,4]:
... if i == 3:
... print(i)
... else:
... print('not 3.')
...
not 3.
not 3.
3
not 3.
>>> dave = 'hungry'
>>> n = 0
>>> while dave == 'hungry':
... print('feeding dave')
... n += 1
... if n == 5:
... dave = 'full'
...
feeding dave
feeding dave
feeding dave
feeding dave
feeding dave
>>> print(dave)
full
- str.format() – formatting a string documentation (this is good stuff!)
>>> 'hello, {0}'.format('dave')
'hello, dave'
>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> '{:^30}'.format('centered')
' centered '