An (Inaccurate) Introduction to Python

62
to... NortHACKton

description

This is a presentation I gave to a recent NortHACKton meeting. The audience were a mixture of seasoned developers who were new to Python and complete newbies who'd never coded anything before. In the end everyone created a Parrot class and did a show and tell of their code to the rest of the group. Find out about NortHACKton here: http://northackton.stdin.co.uk/blog/

Transcript of An (Inaccurate) Introduction to Python

Page 1: An (Inaccurate) Introduction to Python

to...

NortHACKton

Page 2: An (Inaccurate) Introduction to Python

Why?

Page 3: An (Inaccurate) Introduction to Python

•Easy to learn

•Multi paradigm

•Extensive library

•Great community

•Fun!

Page 4: An (Inaccurate) Introduction to Python

http://python.org/download/(for now use the 2.7 version)

Page 5: An (Inaccurate) Introduction to Python

>>> print "Hello, World!"

“Hello, World!”

Page 6: An (Inaccurate) Introduction to Python

“Hello, World!”

$ pythonPython 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) [GCC 4.2.1 (Apple Inc. build 5646)] on darwinType "help", "copyright", "credits" or "license" for more information.>>> print "Hello, World!"Hello, World!

Page 7: An (Inaccurate) Introduction to Python

“Hello, World!”

$ pythonPython 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) [GCC 4.2.1 (Apple Inc. build 5646)] on darwinType "help", "copyright", "credits" or "license" for more information.>>> print "Hello, World!"Hello, World!

Start the Python interpreter from the command line

Page 8: An (Inaccurate) Introduction to Python

“Hello, World!”

$ pythonPython 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) [GCC 4.2.1 (Apple Inc. build 5646)] on darwinType "help", "copyright", "credits" or "license" for more information.>>> print "Hello, World!"Hello, World! Generic information about the

Python interpreter.

Page 9: An (Inaccurate) Introduction to Python

“Hello, World!”

$ pythonPython 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) [GCC 4.2.1 (Apple Inc. build 5646)] on darwinType "help", "copyright", "credits" or "license" for more information.>>> print "Hello, World!"Hello, World!

You type this bit...

Page 10: An (Inaccurate) Introduction to Python

“Hello, World!”

$ pythonPython 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) [GCC 4.2.1 (Apple Inc. build 5646)] on darwinType "help", "copyright", "credits" or "license" for more information.>>> print "Hello, World!"Hello, World!

Python returns the result (you made that happen!)

Page 11: An (Inaccurate) Introduction to Python

“Hello, World!” function

def hello(name="World!"): """ Makes Python say hello.

:param name: who to greet """ return "Hello, %s" % name

Page 12: An (Inaccurate) Introduction to Python

def hello(name="World!"): """ Makes Python say hello.

:param name: who to greet """ return "Hello, %s" % name

Functions are named blocks of code that do stuff.

“Hello, World!” function

Page 13: An (Inaccurate) Introduction to Python

def hello(name="World!"): """ Makes Python say hello.

:param name: who to greet """ return "Hello, %s" % name

def = define

“Hello, World!” function

Page 14: An (Inaccurate) Introduction to Python

def hello(name="World!"): """ Makes Python say hello.

:param name: who to greet """ return "Hello, %s" % name

hello = name of function

“Hello, World!” function

Page 15: An (Inaccurate) Introduction to Python

def hello(name="World!"): """ Makes Python say hello.

:param name: who to greet """ return "Hello, %s" % name

an argument (input) into the function

“Hello, World!” function

Page 16: An (Inaccurate) Introduction to Python

def hello(name="World!"): """ Makes Python say hello.

:param name: who to greet """ return "Hello, %s" % name

a default value for the name arg

“Hello, World!” function

Page 17: An (Inaccurate) Introduction to Python

def hello(name="World!"): """ Makes Python say hello.

:param name: who to greet """ return "Hello, %s" % name

Whitespace (a 4 space indent) indicates scope

“Hello, World!” function

Page 18: An (Inaccurate) Introduction to Python

def hello(name="World!"): """ Makes Python say hello.

:param name: who to greet """ return "Hello, %s" % name

comments& docs

“Hello, World!” function

Page 19: An (Inaccurate) Introduction to Python

def hello(name="World!"): """ Makes Python say hello.

:param name: who to greet """ return "Hello, %s" % name

return = result

“Hello, World!” function

Page 20: An (Inaccurate) Introduction to Python

def hello(name="World!"): """ Makes Python say hello.

:param name: who to greet """ return "Hello, %s" % name

a string (use either ' or ")

“Hello, World!” function

Page 21: An (Inaccurate) Introduction to Python

def hello(name="World!"): """ Makes Python say hello.

:param name: who to greet """ return "Hello, %s" % name

string formatting

“Hello, World!” function

Page 22: An (Inaccurate) Introduction to Python

>>> hello()'Hello, World!'>>> hello("NortHACKton")'Hello, NortHACKton'>>> hello("Widget")'Hello, Widget'

Call the function (note the brackets)

Page 23: An (Inaccurate) Introduction to Python

>>> hello()'Hello, World!'>>> hello("NortHACKton")'Hello, NortHACKton'>>> hello("Widget")'Hello, Widget'

Here’s the result...

Page 24: An (Inaccurate) Introduction to Python

>>> hello()'Hello, World!'>>> hello("NortHACKton")'Hello, NortHACKton'>>> hello("Widget")'Hello, Widget'

Aha! Pass in arguments between the brackets...

Page 25: An (Inaccurate) Introduction to Python

HELP!>>> dir()['__builtins__', '__doc__', '__name__', '__package__', 'hello']>>> help(hello)Help on function hello in module __main__:

hello(name='World!') Makes Python say hello. :param name: who to greet

Page 26: An (Inaccurate) Introduction to Python

HELP!>>> dir()['__builtins__', '__doc__', '__name__', '__package__', 'hello']>>> help(hello)Help on function hello in module __main__:

hello(name='World!') Makes Python say hello. :param name: who to greet

return the attributes of given scope

display help from docstring

Page 27: An (Inaccurate) Introduction to Python

Assignment>>> greeting = hello('NortHACKton!')>>> greeting'Hello, NortHACKton!'>>> type(greeting)<type 'str'>>>> foo = 1>>> type(foo)<type 'int'>>>> bar = 1.234>>> type(bar)<type 'float'>>>> dir(greeting)['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

Page 28: An (Inaccurate) Introduction to Python

Assignment>>> greeting = hello('NortHACKton!')>>> greeting'Hello, NortHACKton!'>>> type(greeting)<type 'str'>>>> foo = 1>>> type(foo)<type 'int'>>>> bar = 1.234>>> type(bar)<type 'float'>>>> dir(greeting)['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

greeting holds the return value

and it’s a string (of characters)!

Page 29: An (Inaccurate) Introduction to Python

Assignment>>> greeting = hello('NortHACKton!')>>> greeting'Hello, NortHACKton!'>>> type(greeting)<type 'str'>>>> foo = 1>>> type(foo)<type 'int'>>>> bar = 1.234>>> type(bar)<type 'float'>>>> dir(greeting)['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

foo holds the number 1and it’s an integer (whole number)!

Page 30: An (Inaccurate) Introduction to Python

Assignment>>> greeting = hello('NortHACKton!')>>> greeting'Hello, NortHACKton!'>>> type(greeting)<type 'str'>>>> foo = 1>>> type(foo)<type 'int'>>>> bar = 1.234>>> type(bar)<type 'float'>>>> dir(greeting)['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

bar holds the number 1.234and it’s a float (’ing point number)!

Page 31: An (Inaccurate) Introduction to Python

Assignment>>> greeting = hello('NortHACKton!')>>> greeting'Hello, NortHACKton!'>>> type(greeting)<type 'str'>>>> foo = 1>>> type(foo)<type 'int'>>>> bar = 1.234>>> type(bar)<type 'float'>>>> dir(greeting)['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

remember this..?

Page 32: An (Inaccurate) Introduction to Python

Assignment>>> greeting = hello('NortHACKton!')>>> greeting'Hello, NortHACKton!'>>> type(greeting)<type 'str'>>>> foo = 1>>> type(foo)<type 'int'>>>> bar = 1.234>>> type(bar)<type 'float'>>>> dir(greeting)['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

All of the attributes/functions of “greeting”

Page 33: An (Inaccurate) Introduction to Python

Program flow...

>>> world_is_flat = False>>> if world_is_flat:... print "The world is flat!"... else:... print "The world is round"... The world is round

Page 34: An (Inaccurate) Introduction to Python

Program flow...

>>> world_is_flat = False>>> if world_is_flat:... print "The world is flat!"... else:... print "The world is round"... The world is round

“if” tests for truth

“else” if “if” evaluates to false

The result of this logic...

Page 35: An (Inaccurate) Introduction to Python

Program flow...

>>> world_is_flat = False>>> if world_is_flat:... print "The world is flat!"... else:... print "The world is round"... The world is round

NB: there is NO switch in Python. Use elif for further clauses in the logic.

Page 36: An (Inaccurate) Introduction to Python

Loops>>> for number in range(10):... print number...

Basically, for each “something” in a group of “somethings” do something

(for each number in a group of numbers print the number)

Page 37: An (Inaccurate) Introduction to Python

Loops>>> for number in range(10):... print number... 0123456789

There’s also while

Like many programming languages, Python starts counting from 0 (zero)

Page 38: An (Inaccurate) Introduction to Python

>>> my_dictionary = { ... 'key': 'value',... 1: 2,... 'branch': { ... 'leaf': 'node'... }... }>>> my_dictionary['key']'value'>>> my_dictionary[1]2>>> my_dictionary['branch']['leaf']'node'>>> my_dictionary{1: 2, 'branch': {'leaf': 'node'}, 'key': 'value'}

dict = key/value store(think phone book)

get the value from the dict

Why not try dir(my_dictionary)and play.?

Data structurescurly brackets!

Page 39: An (Inaccurate) Introduction to Python

Data structures>>> shopping = ['eggs', 'ham', 'spam', 'parrot']>>> len(shopping)4>>> shopping['eggs', 'ham', 'spam', 'parrot']>>> shopping[0]'eggs' >>> shopping[3]'parrot'>>> shopping[4]Traceback (most recent call last): File "<stdin>", line 1, in <module>IndexError: list index out of range>>> shopping[1:]['ham', 'spam', 'parrot']>>> shopping[:1]['eggs']>>> shopping[:-1]['eggs', 'ham', 'spam']>>> shopping[-1:]['parrot']

a list

lists remain in order

get a specific item by position

start counting from zero (remember?)

slicing

square brackets!

Page 40: An (Inaccurate) Introduction to Python
Page 41: An (Inaccurate) Introduction to Python

import antigravityfrom antigravity import stasisfield

stasisfield.generate()

Modules

Page 42: An (Inaccurate) Introduction to Python

OOP(s)

Page 43: An (Inaccurate) Introduction to Python

In a nutshell(there’s much more to it than this)

Classes define sorts of things

Objects are instances of classes

Page 44: An (Inaccurate) Introduction to Python

Cow = class

Buttercup = object (an instance of cow)

Page 45: An (Inaccurate) Introduction to Python

In a nutshell (part 2)(there’s still much more to it than this)

Methods do things (they’re functions)

Attributes define, er, attributes...

Page 46: An (Inaccurate) Introduction to Python

Buttercup.breed = “friesian”

Buttercup.moo()Moo!

Page 47: An (Inaccurate) Introduction to Python

A very simple view...

Nouns = ClassesProper Nouns = Objects

Verbs = MethodsAdjectives = Attributes

er, sort of... I’m making this up as I go along... :-)

Page 48: An (Inaccurate) Introduction to Python

class Cow(object): """ A pythonic cow """

def __init__(self, name="Cow", breed=None): """ Called when the class is instantiated """ self.name = name self.breed = breed

def moo(self, message="MOO!"): """ A bovine hello world! """ return "%s says, %s" % (self.name, message)

Page 49: An (Inaccurate) Introduction to Python

Indicates we’re defining a new class...

class Cow(object): """ A pythonic cow """

def __init__(self, name="Cow", breed=None): """ Called when the class is instantiated """ self.name = name self.breed = breed

def moo(self, message="MOO!"): """ A bovine hello world! """ return "%s says, %s" % (self.name, message)

Page 50: An (Inaccurate) Introduction to Python

... that we’re calling “Cow”...

class Cow(object): """ A pythonic cow """

def __init__(self, name="Cow", breed=None): """ Called when the class is instantiated """ self.name = name self.breed = breed

def moo(self, message="MOO!"): """ A bovine hello world! """ return "%s says, %s" % (self.name, message)

Page 51: An (Inaccurate) Introduction to Python

... that inherits attributes/behaviour from the“object” class.

class Cow(object): """ A pythonic cow """

def __init__(self, name="Cow", breed=None): """ Called when the class is instantiated """ self.name = name self.breed = breed

def moo(self, message="MOO!"): """ A bovine hello world! """ return "%s says, %s" % (self.name, message)

Page 52: An (Inaccurate) Introduction to Python

A docstring that explains what this class represents

class Cow(object): """ A pythonic cow """

def __init__(self, name="Cow", breed=None): """ Called when the class is instantiated """ self.name = name self.breed = breed

def moo(self, message="MOO!"): """ A bovine hello world! """ return "%s says, %s" % (self.name, message)

Page 53: An (Inaccurate) Introduction to Python

class Cow(object): """ A pythonic cow """

def __init__(self, name="Cow", breed=None): """ Called when the class is instantiated """ self.name = name self.breed = breed

def moo(self, message="MOO!"): """ A bovine hello world! """ return "%s says, %s" % (self.name, message)

A special method

called when a new

object is created with this

class

Page 54: An (Inaccurate) Introduction to Python

class Cow(object): """ A pythonic cow """

def __init__(self, name="Cow", breed=None): """ Called when the class is instantiated """ self.name = name self.breed = breed

def moo(self, message="MOO!"): """ A bovine hello world! """ return "%s says, %s" % (self.name, message)

“self” refers to the new object (e.g. Buttercup)

Page 55: An (Inaccurate) Introduction to Python

class Cow(object): """ A pythonic cow """

def __init__(self, name="Cow", breed=None): """ Called when the class is instantiated """ self.name = name self.breed = breed

def moo(self, message="MOO!"): """ A bovine hello world! """ return "%s says, %s" % (self.name, message)

self.name and self.breed are attributes of the instantiated object

(Buttercup)

Page 56: An (Inaccurate) Introduction to Python

class Cow(object): """ A pythonic cow """

def __init__(self, name="Cow", breed=None): """ Called when the class is instantiated """ self.name = name self.breed = breed

def moo(self, message="MOO!"): """ A bovine hello world! """ return "%s says, %s" % (self.name, message)

A method makes the object do something

Page 57: An (Inaccurate) Introduction to Python

>>> from example import Cow>>> buttercup = cow("Buttercup", "friesian")>>> buttercup.name'Buttercup'>>> buttercup.breed'friesian'>>> buttercup.moo()'Buttercup says, MOO!'

Page 59: An (Inaccurate) Introduction to Python

and now for something completely different...

Page 60: An (Inaccurate) Introduction to Python

Your task:Create a Parrot class. It must be able to squawk, flap and, ahem, become deceased. If the parrot is deceased then

calling squawk and flap return the message “This is an ex-parrot”. We should be able to indicate the parrot’s breed

and give it a name. Use your imagination! HAVE FUN!

Page 61: An (Inaccurate) Introduction to Python

Show and tell...

Page 62: An (Inaccurate) Introduction to Python

End (the)http://python.org/