to... NortHACKton
Why?
•Easy to learn • Multi paradigm • Extensive library • Great community • Fun!
http://python.org/download/ (for now use the 2.7 version)
“Hello, World!” >>> print "Hello, World!"
“Hello, World!” $ python Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> print "Hello, World!" Hello, World!
“Hello, World!” Start the Python interpreter $ python from the command line Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> print "Hello, World!" Hello, World!
“Hello, World!” $ python Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> print "Hello, World!" Hello, World! Generic information about the Python interpreter.
“Hello, World!” $ python Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> print "Hello, World!" Hello, World! You type this bit...
“Hello, World!” $ python Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "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
“Hello, World!” function Functions are named blocks of code that do stuff. def hello(name="World!"): """ Makes Python say hello. :param name: who to greet """ return "Hello, %s" % name
“Hello, World!” function def = define def hello(name="World!"): """ Makes Python say hello. :param name: who to greet """ return "Hello, %s" % name
“Hello, World!” function hello = name of function def hello(name="World!"): """ Makes Python say hello. :param name: who to greet """ return "Hello, %s" % name
“Hello, World!” function an argument (input) into the function def hello(name="World!"): """ Makes Python say hello. :param name: who to greet """ return "Hello, %s" % name
“Hello, World!” function a default value for the name arg def hello(name="World!"): """ Makes Python say hello. :param name: who to greet """ return "Hello, %s" % name
“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. comments & docs :param name: who to greet """ return "Hello, %s" % name
“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
Call the function (note the brackets) >>> hello() 'Hello, World!' >>> hello("NortHACKton") 'Hello, NortHACKton' >>> hello("Widget") 'Hello, Widget'
>>> hello() Here’s the result... 'Hello, World!' >>> hello("NortHACKton") 'Hello, NortHACKton' >>> hello("Widget") 'Hello, Widget'
>>> 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() return the attributes of given scope ['__builtins__', '__doc__', '__name__', '__package__', 'hello'] >>> help(hello) display help from docstring Help on function hello in module __main__: hello(name='World!') Makes Python say hello. :param name: who to greet
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 greeting holds the return value 'Hello, NortHACKton!' and it’s a string (of characters)! >>> 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) foo holds the number 1 <type 'str'> >>> foo = 1 >>> type(foo) <type 'int'> >>> bar = 1.234 and it’s an integer (whole number)! >>> 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) bar holds the number 1.234 <type 'int'> >>> bar = 1.234 >>> type(bar) <type 'float'> >>> dir(greeting) and it’s a float (’ing point number)! ['__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) remember this..? ['__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'] 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: “if” tests for truth ... print "The world is flat!" ... else: “else” if “if” evaluates to false ... print "The world is round" ... The world is round 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 ... 0 1 2 3 Like many programming languages, 4 Python starts counting from 0 (zero) 5 6 7 8 9 There’s also while
Data structures >>> my_dictionary = { curly brackets! ... 'key': 'value', ... 1: 2, dict = key/value store ... 'branch': { ... 'leaf': 'node' (think phone book) ... } ... } >>> my_dictionary['key'] get the value from the dict 'value' >>> my_dictionary[1] 2 >>> my_dictionary['branch']['leaf'] 'node' >>> my_dictionary {1: 2, 'branch': {'leaf': 'node'}, 'key': 'value'} Why not try dir(my_dictionary)and play.?
Data structures >>> shopping = ['eggs', 'ham', 'spam', 'parrot'] a list >>> len(shopping) 4 square brackets! >>> shopping ['eggs', 'ham', 'spam', 'parrot'] lists remain in order >>> shopping[0] 'eggs' >>> shopping[3] get a specific item by position 'parrot' >>> shopping[4] Traceback (most recent call last): start counting from File "<stdin>", line 1, in <module> IndexError: list index out of range zero (remember?) >>> shopping[1:] ['ham', 'spam', 'parrot'] >>> shopping[:1] ['eggs'] >>> shopping[:-1] slicing ['eggs', 'ham', 'spam'] >>> shopping[-1:] ['parrot']
Modules import antigravity from antigravity import stasisfield stasisfield.generate()
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...
Moo! Buttercup.moo() Buttercup.breed = “friesian”
A very simple view... Nouns = Classes Proper Nouns = Objects Verbs = Methods Adjectives = 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)
class Cow(object): A docstring that explains """ A pythonic cow what this class represents """ 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): """ A special Called when the class is instantiated """ method self.name = name self.breed = breed called when a new def moo(self, message="MOO!"): """ object is A bovine hello world! """ created return "%s says, %s" % (self.name, message) with this class
class Cow(object): """ A pythonic cow “self” refers to the new """ object (e.g. Buttercup) 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.name and self.breed self.breed = breed are attributes of the def moo(self, message="MOO!"): instantiated object """ A bovine hello world! (Buttercup) """ 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! A method """ return "%s says, %s" % (self.name, message) 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...
End (the) http://python.org/

An (Inaccurate) Introduction to Python

  • 1.
  • 2.
  • 3.
    •Easy to learn •Multi paradigm • Extensive library • Great community • Fun!
  • 4.
    http://python.org/download/ (for now use the 2.7 version)
  • 5.
  • 6.
    “Hello, World!” $ python Python2.6.1 (r261:67515, Jun 24 2010, 21:47:49) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> print "Hello, World!" Hello, World!
  • 7.
    “Hello, World!” Start the Python interpreter $ python from the command line Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> print "Hello, World!" Hello, World!
  • 8.
    “Hello, World!” $ python Python2.6.1 (r261:67515, Jun 24 2010, 21:47:49) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> print "Hello, World!" Hello, World! Generic information about the Python interpreter.
  • 9.
    “Hello, World!” $ python Python2.6.1 (r261:67515, Jun 24 2010, 21:47:49) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> print "Hello, World!" Hello, World! You type this bit...
  • 10.
    “Hello, World!” $ python Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> print "Hello, World!" Hello, World! Python returns the result (you made that happen!)
  • 11.
    “Hello, World!” function def hello(name="World!"): """ Makes Python say hello. :param name: who to greet """ return "Hello, %s" % name
  • 12.
    “Hello, World!” function Functionsare named blocks of code that do stuff. def hello(name="World!"): """ Makes Python say hello. :param name: who to greet """ return "Hello, %s" % name
  • 13.
    “Hello, World!” function def= define def hello(name="World!"): """ Makes Python say hello. :param name: who to greet """ return "Hello, %s" % name
  • 14.
    “Hello, World!” function hello= name of function def hello(name="World!"): """ Makes Python say hello. :param name: who to greet """ return "Hello, %s" % name
  • 15.
    “Hello, World!” function anargument (input) into the function def hello(name="World!"): """ Makes Python say hello. :param name: who to greet """ return "Hello, %s" % name
  • 16.
    “Hello, World!” function a default value for the name arg def hello(name="World!"): """ Makes Python say hello. :param name: who to greet """ return "Hello, %s" % name
  • 17.
    “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
  • 18.
    “Hello, World!” function def hello(name="World!"): """ Makes Python say hello. comments & docs :param name: who to greet """ return "Hello, %s" % name
  • 19.
    “Hello, World!” function def hello(name="World!"): """ Makes Python say hello. :param name: who to greet """ return "Hello, %s" % name return = result
  • 20.
    “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 ")
  • 21.
    “Hello, World!” function def hello(name="World!"): """ Makes Python say hello. :param name: who to greet """ return "Hello, %s" % name string formatting
  • 22.
    Call the function(note the brackets) >>> hello() 'Hello, World!' >>> hello("NortHACKton") 'Hello, NortHACKton' >>> hello("Widget") 'Hello, Widget'
  • 23.
    >>> hello() Here’s the result... 'Hello, World!' >>> hello("NortHACKton") 'Hello, NortHACKton' >>> hello("Widget") 'Hello, Widget'
  • 24.
    >>> hello() 'Hello, World!' >>> hello("NortHACKton") 'Hello, NortHACKton' >>> hello("Widget") 'Hello, Widget' Aha! Pass in arguments between the brackets...
  • 25.
    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
  • 26.
    HELP! >>> dir() return the attributes of given scope ['__builtins__', '__doc__', '__name__', '__package__', 'hello'] >>> help(hello) display help from docstring Help on function hello in module __main__: hello(name='World!') Makes Python say hello. :param name: who to greet
  • 27.
    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']
  • 28.
    Assignment >>> greeting =hello('NortHACKton!') >>> greeting greeting holds the return value 'Hello, NortHACKton!' and it’s a string (of characters)! >>> 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']
  • 29.
    Assignment >>> greeting =hello('NortHACKton!') >>> greeting 'Hello, NortHACKton!' >>> type(greeting) foo holds the number 1 <type 'str'> >>> foo = 1 >>> type(foo) <type 'int'> >>> bar = 1.234 and it’s an integer (whole number)! >>> 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']
  • 30.
    Assignment >>> greeting =hello('NortHACKton!') >>> greeting 'Hello, NortHACKton!' >>> type(greeting) <type 'str'> >>> foo = 1 >>> type(foo) bar holds the number 1.234 <type 'int'> >>> bar = 1.234 >>> type(bar) <type 'float'> >>> dir(greeting) and it’s a float (’ing point number)! ['__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']
  • 31.
    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) remember this..? ['__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']
  • 32.
    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”
  • 33.
    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
  • 34.
    Program flow... >>> world_is_flat = False >>> if world_is_flat: “if” tests for truth ... print "The world is flat!" ... else: “else” if “if” evaluates to false ... print "The world is round" ... The world is round The result of this logic...
  • 35.
    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.
  • 36.
    Loops >>> for numberin 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)
  • 37.
    Loops >>> for numberin range(10): ... print number ... 0 1 2 3 Like many programming languages, 4 Python starts counting from 0 (zero) 5 6 7 8 9 There’s also while
  • 38.
    Data structures >>> my_dictionary = { curly brackets! ... 'key': 'value', ... 1: 2, dict = key/value store ... 'branch': { ... 'leaf': 'node' (think phone book) ... } ... } >>> my_dictionary['key'] get the value from the dict 'value' >>> my_dictionary[1] 2 >>> my_dictionary['branch']['leaf'] 'node' >>> my_dictionary {1: 2, 'branch': {'leaf': 'node'}, 'key': 'value'} Why not try dir(my_dictionary)and play.?
  • 39.
    Data structures >>> shopping= ['eggs', 'ham', 'spam', 'parrot'] a list >>> len(shopping) 4 square brackets! >>> shopping ['eggs', 'ham', 'spam', 'parrot'] lists remain in order >>> shopping[0] 'eggs' >>> shopping[3] get a specific item by position 'parrot' >>> shopping[4] Traceback (most recent call last): start counting from File "<stdin>", line 1, in <module> IndexError: list index out of range zero (remember?) >>> shopping[1:] ['ham', 'spam', 'parrot'] >>> shopping[:1] ['eggs'] >>> shopping[:-1] slicing ['eggs', 'ham', 'spam'] >>> shopping[-1:] ['parrot']
  • 41.
    Modules import antigravity from antigravityimport stasisfield stasisfield.generate()
  • 42.
  • 43.
    In a nutshell (there’s much more to it than this) Classes define sorts of things Objects are instances of classes
  • 44.
    Cow = class Buttercup= object (an instance of cow)
  • 45.
    In a nutshell(part 2) (there’s still much more to it than this) Methods do things (they’re functions) Attributes define, er, attributes...
  • 46.
    Moo! Buttercup.moo() Buttercup.breed = “friesian”
  • 47.
    A very simpleview... Nouns = Classes Proper Nouns = Objects Verbs = Methods Adjectives = Attributes er, sort of... I’m making this up as I go along... :-)
  • 48.
    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)
  • 49.
    Indicates we’re defininga 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)
  • 50.
    ... that we’recalling “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)
  • 51.
    ... that inheritsattributes/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)
  • 52.
    class Cow(object): A docstring that explains """ A pythonic cow what this class represents """ 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)
  • 53.
    class Cow(object): """ A pythonic cow """ def __init__(self, name="Cow", breed=None): """ A special Called when the class is instantiated """ method self.name = name self.breed = breed called when a new def moo(self, message="MOO!"): """ object is A bovine hello world! """ created return "%s says, %s" % (self.name, message) with this class
  • 54.
    class Cow(object): """ A pythonic cow “self” refers to the new """ object (e.g. Buttercup) 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)
  • 55.
    class Cow(object): """ A pythonic cow """ def __init__(self, name="Cow", breed=None): """ Called when the class is instantiated """ self.name = name self.name and self.breed self.breed = breed are attributes of the def moo(self, message="MOO!"): instantiated object """ A bovine hello world! (Buttercup) """ return "%s says, %s" % (self.name, message)
  • 56.
    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! A method """ return "%s says, %s" % (self.name, message) makes the object do something
  • 57.
    >>> from exampleimport Cow >>> buttercup = cow("Buttercup", "friesian") >>> buttercup.name 'Buttercup' >>> buttercup.breed 'friesian' >>> buttercup.moo() 'Buttercup says, MOO!'
  • 58.
  • 59.
    and now forsomething completely different...
  • 60.
    Your task: Create aParrot 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!
  • 61.
  • 62.