Sei sulla pagina 1di 19

.

.
Beginning Python
.
.. .

.
Netsoc

Stephen Shaw

2010

Netsoc (Stephen Shaw) <stesh@netsoc.tcd.ie> 2010 1 / 19


Getting started

SSH to one of our servers


$ ssh you@login.netsoc.tcd.ie
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) <stesh@netsoc.tcd.ie> 2010 2 / 19


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) <stesh@netsoc.tcd.ie> 2010 3 / 19


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) <stesh@netsoc.tcd.ie> 2010 4 / 19


Diving into python

We'll use Python 3.1.3


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) <stesh@netsoc.tcd.ie> 2010 5 / 19
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) <stesh@netsoc.tcd.ie> 2010 6 / 19


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, ==, !=, <=, =>,
Multiple assignment and iterable unpacking
Indentation!
Comments begin with a #
Netsoc (Stephen Shaw) <stesh@netsoc.tcd.ie> 2010 7 / 19
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) <stesh@netsoc.tcd.ie> 2010 8 / 19


Lists

Python's equivalent to arrays


The `workhorse'
LISP-like, I'm told
[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) <stesh@netsoc.tcd.ie> 2010 9 / 19
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) <stesh@netsoc.tcd.ie> 2010 10 / 19


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) <stesh@netsoc.tcd.ie> 2010 11 / 19


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) <stesh@netsoc.tcd.ie> 2010 12 / 19


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) <stesh@netsoc.tcd.ie> 2010 13 / 19


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) <stesh@netsoc.tcd.ie> 2010 14 / 19


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) <stesh@netsoc.tcd.ie> 2010 15 / 19
Anonymous functions
Cool
Functions are first-class objects in python
Can pass functions/methods as arguments to other functions/methods
Functions need not be bound to a name
# Sends x to itself raised to the power of 2
lambda x : x **2

# Binding to a name :
capitalize = lambda x : x . upper ()

# Passing a function to a function :


def apply ( function , argument ) :
( function ) ( argument )

Used extensively in map, filter and reduce


A taste of functional programming
Netsoc (Stephen Shaw) <stesh@netsoc.tcd.ie> 2010 16 / 19
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


The with statement is relatively new
Does something vaguely similar to blocks in ruby

Netsoc (Stephen Shaw) <stesh@netsoc.tcd.ie> 2010 17 / 19


Exceptions
No surprises here
Exceptions have a big class hierarchy
raise to raise an exception
try to begin an excepting block
except to `catch'
finally cleaning up

try :
p r i n t ( mydict [ key ])
except KeyError :
p r i n t ( ' Oh noes ! ')

Can often be avoided:


i f key i n mydict :
p r i n t ( mydict [ key ])
else :
p r i n t ( ' Oh noes ! ')
Netsoc (Stephen Shaw) <stesh@netsoc.tcd.ie> 2010 18 / 19
Installing

Linux, OS X: you probably have python installed already


Python is an integral part of most *nixes.
Python 3 is in most repos (there is *usually* a non-broken package in
MacPorts)
Python 3 default in Arch Linux (:-S)
There is a comprehensive python implementation for Windows
I've never tried it, so can't offer any advice there
Questions?

Netsoc (Stephen Shaw) <stesh@netsoc.tcd.ie> 2010 19 / 19

Potrebbero piacerti anche