SlideShare a Scribd company logo
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/

More Related Content

What's hot

Ohm
OhmOhm
PHP 5.4
PHP 5.4PHP 5.4
Ruby - Uma Introdução
Ruby - Uma IntroduçãoRuby - Uma Introdução
Ruby - Uma Introdução
Ígor Bonadio
 
Pre-Bootcamp introduction to Elixir
Pre-Bootcamp introduction to ElixirPre-Bootcamp introduction to Elixir
Pre-Bootcamp introduction to Elixir
Paweł Dawczak
 
(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
 
Communities - Perl edition (RioJS)
Communities - Perl edition (RioJS)Communities - Perl edition (RioJS)
Communities - Perl edition (RioJS)
garux
 
Python chapter 2
Python chapter 2Python chapter 2
Python chapter 2Raghu nath
 
python chapter 1
python chapter 1python chapter 1
python chapter 1Raghu nath
 
PHP 1
PHP 1PHP 1
PubNative Tracker
PubNative TrackerPubNative Tracker
PubNative Tracker
Andrew Djoga
 
Elixir cheatsheet
Elixir cheatsheetElixir cheatsheet
Elixir cheatsheet
Héla Ben Khalfallah
 
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...
David Koelle
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a boss
gsterndale
 
Symfony2 - extending the console component
Symfony2 - extending the console componentSymfony2 - extending the console component
Symfony2 - extending the console component
Hugo Hamon
 
Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB jhchabran
 
Potential Friend Finder
Potential Friend FinderPotential Friend Finder
Potential Friend Finder
Richard Schneeman
 
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]
David Koelle
 
Palestra sobre Collections com Python
Palestra sobre Collections com PythonPalestra sobre Collections com Python
Palestra sobre Collections com Pythonpugpe
 

What's hot (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
 

Viewers also liked

FluidDB for Dummies
FluidDB for DummiesFluidDB for Dummies
FluidDB for Dummies
Nicholas Tollervey
 
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
alianzabosques
 
FluidDB in a Nutshell
FluidDB in a NutshellFluidDB in a Nutshell
FluidDB in a Nutshell
Nicholas Tollervey
 
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
Alexander Decker
 
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
Nicholas Tollervey
 

Viewers also liked (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 to An (Inaccurate) Introduction to Python

PHP Basics and Demo HackU
PHP Basics and Demo HackUPHP Basics and Demo HackU
PHP Basics and Demo HackU
Anshu Prateek
 
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
Matt Harrison
 
An introduction to Ruby
An introduction to RubyAn introduction to Ruby
An introduction to Ruby
Wes Oldenbeuving
 
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
 
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
Rodrigo Senra
 
Internationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsInternationalizing CakePHP Applications
Internationalizing CakePHP Applications
Pierre MARTIN
 
PHP and MySQL
PHP and MySQLPHP and MySQL
PHP and MySQL
Sanketkumar Biswas
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
Muthu Vinayagam
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
Ahmed Salama
 
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
SovannDoeur
 
python beginner talk slide
python beginner talk slidepython beginner talk slide
python beginner talk slide
jonycse
 
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
Utkarsh Sengar
 
Achieving Parsing Sanity In Erlang
Achieving Parsing Sanity In ErlangAchieving Parsing Sanity In Erlang
Achieving Parsing Sanity In Erlang
Sean Cribbs
 
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
Sumit Raj
 
Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Wen-Tien Chang
 
Fantom and Tales
Fantom and TalesFantom and Tales
Fantom and Tales
kaushik_sathupadi
 
Blog Hacks 2011
Blog Hacks 2011Blog Hacks 2011
Blog Hacks 2011
Yusuke Wada
 
Ch1(introduction to php)
Ch1(introduction to php)Ch1(introduction to php)
Ch1(introduction to php)
Chhom Karath
 
Python Workshop
Python  Workshop Python  Workshop
Python Workshop
Assem CHELLI
 

Similar to 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
 

Recently uploaded

Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 

Recently uploaded (20)

Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 

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!