.
.
Beginning Python
.
.. .
.
Netsoc
Stephen Shaw
2010
Netsoc (Stephen Shaw) <[email protected]> 2010 1 / 20
Getting started
SSH to one of our servers
$ ssh
[email protected] PuTTY: Enter login.netsoc.tcd.ie as the hostname
NX on cube if you want - all you need is a shell though
No netsoc account?
CS: macneill.scss.tcd.ie
Maths servers?
Talk to an admin before you leave so you have an account for next time
Netsoc (Stephen Shaw) <[email protected]> 2010 2 / 20
The plan
Schedule
This week - The basics
Week 2 - Modules, packages, the PYPI, Hacking up text with python -
screen scraping, regular expressions, unicode
Week 3 - Miscellaneous fun (maybe a bit of PyGame?)
Most likely in the Arts Building Mac labs next week - details later in the
week
These slides: http://www.netsoc.tcd.ie/~stesh/python/1.pdf
Netsoc (Stephen Shaw) <[email protected]> 2010 3 / 20
About python
Duck-typed, multiparadigm, general-purpose programming language
Born in the late '80s - older than Java
Awesome!
Python is an interpreted language (sort of)
Hacking up things
Google, YouTube, (netsoc!)
Libraries for almost any conceivable task
Netsoc (Stephen Shaw) <[email protected]> 2010 4 / 20
Diving into python
We'll use Python 3.1.2
At the prompt, type python3
stesh@spoon : ˜ [18:10]% python3
Python 3.1.3 ( r313 :86834 , Nov 28 2010 , 10:01:07)
[ GCC 4.4.5] on linux2
Type " help " , " copyright " , " credits " or " license " �
for more information .
>>>
You're now in the REPL - Read-Eval-Print-Loop
Python reads an expression from you, evaluates it, and prints it
Try it now!
If you don't know how something words, type help(thething)
Usual mathematical operators. Use ** for exponentiation
Netsoc (Stephen Shaw) <
[email protected]> 2010 5 / 20
Functions
Functions look like this:
def area ( radius ) :
i f radius < 0:
radius = - radius
pi = 3.14
return pi * r **2
No need to say what types variables have
Variables can change type any time
Indentation - very important
Different indentation changes the meaning of your program!
Line-ending semicolons are optional
Netsoc (Stephen Shaw) <[email protected]> 2010 6 / 20
If, else
x, y = 4, 6
i f x != 5 and y < 100:
something ()
e l i f x % 2 == 0 or 0 < x < y < 34:
something_else ()
e l i f not ( True or False ) :
something_different () # Will never run
else :
stuff ()
Only need parentheses when things are ambiguous
and, or, not, ==, !=, <=, =>,
Indentation!
Comments begin with a #
Netsoc (Stephen Shaw) <[email protected]> 2010 7 / 20
Loops
ministers = [ ' Mary ' , ' Batt ' , ' Noel ' , ' Dermott ']
f o r minister i n ministers :
p r i n t ( minister + " has retired ! " )
f o r beatle i n { ' Ringo ' , ' George ' , ' Paul ' , ' John ' }:
p r i n t ( beatle )
f o r c i n ' Stephen ':
print (c)
f o r word i n ' This is a sentence '. split () :
p r i n t ( word )
Netsoc (Stephen Shaw) <[email protected]> 2010 8 / 20
Lists
Python's equivalent to arrays
The `workhorse'
[1, 2, 3, 4, 5]
List of strings the lazy way:
mylist = 'A big long list of strings'.split()
Lists are mutable (change their size whenever you want):
mylist.append(element)
Lists can hold anything, including objects of different types:
['a string', 1, True, ['2']]
Add lists to other lists: [1, 2, 3, 4] + [5, 6, 7, 8] →
[1, 2, 3, 4, 5, 6, 7, 8]
Reversing: reversed(mylist)
Sorting: sorted(mylist)
Netsoc (Stephen Shaw) <[email protected]> 2010 9 / 20
Slicing
Access elements with [] notation: mylist[2] returns 'long'
Much richer than that:
mylist[1:] - `Everything except the first index'
mylist[5:10] - `All indices from 5 inclusive to 10'
mylist[5:10:2] - `All indices from 5 inclusive to 10, counting up in twos'
mylist[:-2] - `Everything except the last two indices'
mylist[1:-1] - `Everything except the first and last indices'
mylist[::] - `All indices'
mylist[::-1] - `All indices, counting from the right (reverse the list)'
Using a list as a stack:
mylist.append(element)
mylist.pop()
Netsoc (Stephen Shaw) <[email protected]> 2010 10 / 20
Sztrings
Replacing: 'DUCSS'.replace('U', 'I')
In most cases, you can treat a string as if it were a list:
'Netsoc'[2] will return t
reversed('apache') gives you a new string 'ehcapa'
'e' in 'Netsoc'
This is because both strings and lists are iterables
Iterables are very widespread in Python
Let's look at some more iterables
Netsoc (Stephen Shaw) <[email protected]> 2010 11 / 20
More about strings
Replacing: 'DUCSS'.replace('U', 'I')
In most cases, you can treat a string as if it were a list:
'Netsoc'[2] will return t
reversed('apache') gives you a new string 'ehcapa'
'e' in 'Netsoc'
This is because both strings and lists are iterables
Iterables are very widespread in Python
Let's look at some more iterables
Netsoc (Stephen Shaw) <[email protected]> 2010 12 / 20
Tuples
A bit like lists, except immutable: (1, 2, 3)
Once a tuple is created, it can't be changed, only accessed
mytuple + (5, 6, 7, 8) creates a whole new tuple
You can make a list from a tuple, and (sometimes) vice-versa:
tuple([1, 2, 3])
`A list is a pencil, a tuple is a pen'
Netsoc (Stephen Shaw) <[email protected]> 2010 13 / 20
Sets
Unordered collection of things with no repeated elements - no
guarantee that elements will come out in the order you put them in
Often really fast
beatles = {'John', 'Paul', 'George', 'Ringo'}
Operations
A.add(element)
A.remove(element)
A.union(B)
A.intersection(B)
A - B
A.difference(B)
A.issubset(B)
Netsoc (Stephen Shaw) <[email protected]> 2010 14 / 20
Comprehensions
Really powerful way to make iterable things
`Give me all the strings in mylist that don't contain a q':
[x for x in mylist if 'q'not in x]
`Give me the set of all the even integers between 0 and 100':
{x for x in range(100)if x % 2 == 0}
`Give me a copy of my list of integers as a list of strings':
[str(x) for x in mylist]
Netsoc (Stephen Shaw) <[email protected]> 2010 15 / 20
Dictionaries
Also very important
council = {
' secretary ': ' br0kend '
' PRO ': ' lux ' ,
' treasurer ': ' dalamar ' ,
' amenities ': ' don ' ,
' auditor ': ' mk429 ' ,
' admin ': ' mu ' ,
' webmaster ': ' theorie '
}
Associate things with other things
council['auditor'] 'mk429'
'admin' in council returns True
Useful when you're counting occurrences of things
Netsoc (Stephen Shaw) <
[email protected]> 2010 16 / 20
Anonymous functions
Also very important
council = {
' secretary ': ' br0kend '
' PRO ': ' lux ' ,
' treasurer ': ' dalamar ' ,
' amenities ': ' don ' ,
' auditor ': ' mk429 ' ,
' admin ': ' mu ' ,
' webmaster ': ' theorie '
}
Associate things with other things
Netsoc (Stephen Shaw) <[email protected]> 2010 17 / 20
Files
Easy!
with myfile as open ( ' myfile . txt ') :
while True :
line = mylist . readline ()
i f line == ' ':
break
dosomething ()
use .read()to read it all at once
Netsoc (Stephen Shaw) <[email protected]> 2010 18 / 20
Exceptions
try
raise
finally
Netsoc (Stephen Shaw) <[email protected]> 2010 19 / 20
Installing
Linux, OS X: you probably have python installed already
Python 3 is in most repos (there is *usually* a non-broken package in
MacPorts)
There is a comprehensive python implementation for Windows
Questions?
Netsoc (Stephen Shaw) <[email protected]> 2010 20 / 20