SlideShare una empresa de Scribd logo
1 de 62
Descargar para leer sin conexión
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/

Más contenido relacionado

La actualidad más candente

(Ab)Using the MetaCPAN API for Fun and Profit
(Ab)Using the MetaCPAN API for Fun and Profit(Ab)Using the MetaCPAN API for Fun and Profit
(Ab)Using the MetaCPAN API for Fun and Profit
Olaf Alders
 
Python chapter 2
Python chapter 2Python chapter 2
Python chapter 2
Raghu nath
 
python chapter 1
python chapter 1python chapter 1
python chapter 1
Raghu nath
 
Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB
jhchabran
 
Palestra sobre Collections com Python
Palestra sobre Collections com PythonPalestra sobre Collections com Python
Palestra sobre Collections com Python
pugpe
 

La actualidad más candente (20)

Ohm
OhmOhm
Ohm
 
PHP 5.4
PHP 5.4PHP 5.4
PHP 5.4
 
Ruby - Uma Introdução
Ruby - Uma IntroduçãoRuby - Uma Introdução
Ruby - Uma Introdução
 
Pre-Bootcamp introduction to Elixir
Pre-Bootcamp introduction to ElixirPre-Bootcamp introduction to Elixir
Pre-Bootcamp introduction to Elixir
 
PHP Tutorial (funtion)
PHP Tutorial (funtion)PHP Tutorial (funtion)
PHP Tutorial (funtion)
 
(Ab)Using the MetaCPAN API for Fun and Profit
(Ab)Using the MetaCPAN API for Fun and Profit(Ab)Using the MetaCPAN API for Fun and Profit
(Ab)Using the MetaCPAN API for Fun and Profit
 
Communities - Perl edition (RioJS)
Communities - Perl edition (RioJS)Communities - Perl edition (RioJS)
Communities - Perl edition (RioJS)
 
Python chapter 2
Python chapter 2Python chapter 2
Python chapter 2
 
python chapter 1
python chapter 1python chapter 1
python chapter 1
 
PHP 1
PHP 1PHP 1
PHP 1
 
PubNative Tracker
PubNative TrackerPubNative Tracker
PubNative Tracker
 
Elixir cheatsheet
Elixir cheatsheetElixir cheatsheet
Elixir cheatsheet
 
The Art, Joy, and Power of Creating Musical Programs (JFugue at SXSW Interact...
The Art, Joy, and Power of Creating Musical Programs (JFugue at SXSW Interact...The Art, Joy, and Power of Creating Musical Programs (JFugue at SXSW Interact...
The Art, Joy, and Power of Creating Musical Programs (JFugue at SXSW Interact...
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a boss
 
Symfony2 - extending the console component
Symfony2 - extending the console componentSymfony2 - extending the console component
Symfony2 - extending the console component
 
Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB
 
Potential Friend Finder
Potential Friend FinderPotential Friend Finder
Potential Friend Finder
 
JFugue, Music, and the Future of Java [JavaOne 2016, CON1851]
JFugue, Music, and the Future of Java [JavaOne 2016, CON1851]JFugue, Music, and the Future of Java [JavaOne 2016, CON1851]
JFugue, Music, and the Future of Java [JavaOne 2016, CON1851]
 
Python 1
Python 1Python 1
Python 1
 
Palestra sobre Collections com Python
Palestra sobre Collections com PythonPalestra sobre Collections com Python
Palestra sobre Collections com Python
 

Destacado (6)

FluidDB for Dummies
FluidDB for DummiesFluidDB for Dummies
FluidDB for Dummies
 
From Territorial Peoples toward a Global Agreement
From Territorial Peoples toward a Global AgreementFrom Territorial Peoples toward a Global Agreement
From Territorial Peoples toward a Global Agreement
 
Blended+learning+&+ibt zul
Blended+learning+&+ibt zulBlended+learning+&+ibt zul
Blended+learning+&+ibt zul
 
FluidDB in a Nutshell
FluidDB in a NutshellFluidDB in a Nutshell
FluidDB in a Nutshell
 
Analysis of linkages between logistics information systems and
Analysis of linkages between logistics information systems andAnalysis of linkages between logistics information systems and
Analysis of linkages between logistics information systems and
 
The London Python Code Dojo - An Education in Developer Education
The London Python Code Dojo - An Education in Developer EducationThe London Python Code Dojo - An Education in Developer Education
The London Python Code Dojo - An Education in Developer Education
 

Similar a An (Inaccurate) Introduction to Python

Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
ConFoo
 
Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Ruby 入門 第一次就上手
Ruby 入門 第一次就上手
Wen-Tien Chang
 

Similar a An (Inaccurate) Introduction to Python (20)

PHP Basics and Demo HackU
PHP Basics and Demo HackUPHP Basics and Demo HackU
PHP Basics and Demo HackU
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
An introduction to Ruby
An introduction to RubyAn introduction to Ruby
An introduction to Ruby
 
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
 
pa-pe-pi-po-pure Python Text Processing
pa-pe-pi-po-pure Python Text Processingpa-pe-pi-po-pure Python Text Processing
pa-pe-pi-po-pure Python Text Processing
 
Internationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsInternationalizing CakePHP Applications
Internationalizing CakePHP Applications
 
PHP and MySQL
PHP and MySQLPHP and MySQL
PHP and MySQL
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Chapter 2 Python Language Basics, IPython.pptx
Chapter 2 Python Language Basics, IPython.pptxChapter 2 Python Language Basics, IPython.pptx
Chapter 2 Python Language Basics, IPython.pptx
 
python beginner talk slide
python beginner talk slidepython beginner talk slide
python beginner talk slide
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
Ruby
RubyRuby
Ruby
 
Achieving Parsing Sanity In Erlang
Achieving Parsing Sanity In ErlangAchieving Parsing Sanity In Erlang
Achieving Parsing Sanity In Erlang
 
An Intro to Python in 30 minutes
An Intro to Python in 30 minutesAn Intro to Python in 30 minutes
An Intro to Python in 30 minutes
 
Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Ruby 入門 第一次就上手
Ruby 入門 第一次就上手
 
Fantom and Tales
Fantom and TalesFantom and Tales
Fantom and Tales
 
Blog Hacks 2011
Blog Hacks 2011Blog Hacks 2011
Blog Hacks 2011
 
Ch1(introduction to php)
Ch1(introduction to php)Ch1(introduction to php)
Ch1(introduction to php)
 
Python Workshop
Python  Workshop Python  Workshop
Python Workshop
 

Último

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Último (20)

A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 

An (Inaccurate) Introduction to Python

  • 3. •Easy to learn • Multi paradigm • Extensive library • Great community • Fun!
  • 4. http://python.org/download/ (for now use the 2.7 version)
  • 6. “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!
  • 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 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.
  • 9. “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...
  • 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 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
  • 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 an argument (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 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)
  • 37. 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
  • 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']
  • 40.
  • 41. Modules import antigravity from antigravity import stasisfield stasisfield.generate()
  • 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 simple view... 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 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)
  • 50. ... 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)
  • 51. ... 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)
  • 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 example import Cow >>> buttercup = cow("Buttercup", "friesian") >>> buttercup.name 'Buttercup' >>> buttercup.breed 'friesian' >>> buttercup.moo() 'Buttercup says, MOO!'
  • 59. and now for something completely different...
  • 60. 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!