an (inaccurate) introduction to python
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
to...
NortHACKton
Why?
•Easy to learn
•Multi paradigm
•Extensive library
•Great community
•Fun!
http://python.org/download/(for now use the 2.7 version)
>>> print "Hello, World!"
“Hello, World!”
“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!
“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
“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.
“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...
“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!)
“Hello, World!” function
def hello(name="World!"): """ Makes Python say hello.
:param name: who to greet """ return "Hello, %s" % name
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
def hello(name="World!"): """ Makes Python say hello.
:param name: who to greet """ return "Hello, %s" % name
def = define
“Hello, World!” function
def hello(name="World!"): """ Makes Python say hello.
:param name: who to greet """ return "Hello, %s" % name
hello = name of function
“Hello, World!” function
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
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
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
def hello(name="World!"): """ Makes Python say hello.
:param name: who to greet """ return "Hello, %s" % name
comments& docs
“Hello, World!” function
def hello(name="World!"): """ Makes Python say hello.
:param name: who to greet """ return "Hello, %s" % name
return = result
“Hello, World!” function
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
def hello(name="World!"): """ Makes Python say hello.
:param name: who to greet """ return "Hello, %s" % name
string formatting
“Hello, World!” function
>>> hello()'Hello, World!'>>> hello("NortHACKton")'Hello, NortHACKton'>>> hello("Widget")'Hello, Widget'
Call the function (note the brackets)
>>> hello()'Hello, World!'>>> hello("NortHACKton")'Hello, NortHACKton'>>> hello("Widget")'Hello, Widget'
Here’s the result...
>>> hello()'Hello, World!'>>> hello("NortHACKton")'Hello, NortHACKton'>>> hello("Widget")'Hello, Widget'
Aha! Pass in arguments between the brackets...
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
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
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']
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)!
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)!
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)!
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..?
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”
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
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...
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.
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)
Loops>>> for number in range(10):... print number... 0123456789
There’s also while
Like many programming languages, Python starts counting from 0 (zero)
>>> 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!
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!
import antigravityfrom antigravity import stasisfield
stasisfield.generate()
Modules
OOP(s)
In a nutshell(there’s much more to it than this)
Classes define sorts of things
Objects are instances of classes
Cow = class
Buttercup = object (an instance of cow)
In a nutshell (part 2)(there’s still much more to it than this)
Methods do things (they’re functions)
Attributes define, er, attributes...
Buttercup.breed = “friesian”
Buttercup.moo()Moo!
A very simple view...
Nouns = ClassesProper Nouns = Objects
Verbs = MethodsAdjectives = Attributes
er, sort of... I’m making this up as I go along... :-)
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)
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)
... 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)
... 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)
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)
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
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)
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)
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
>>> from example import Cow>>> buttercup = cow("Buttercup", "friesian")>>> buttercup.name'Buttercup'>>> buttercup.breed'friesian'>>> buttercup.moo()'Buttercup says, MOO!'
http://docs.python.org/tutorial/introduction.html
and now for something completely different...
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!
Show and tell...