An (Inaccurate) Introduction to Python

2,280 views

Published on

This is a presentation I gave to a recent NortHACKton meeting. The audience were a mixture of seasoned developers who were new to Python and complete newbies who'd never coded anything before.

In the end everyone created a Parrot class and did a show and tell of their code to the rest of the group.

Find out about NortHACKton here: http://northackton.stdin.co.uk/blog/

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
2,280
On SlideShare
0
From Embeds
0
Number of Embeds
9
Actions
Shares
0
Downloads
23
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

An (Inaccurate) Introduction to Python

  1. 1. to...NortHACKton
  2. 2. Why?
  3. 3. •Easy to learn• Multi paradigm• Extensive library• Great community• Fun!
  4. 4. http://python.org/download/ (for now use the 2.7 version)
  5. 5. “Hello, World!”>>> print "Hello, World!"
  6. 6. “Hello, World!”$ pythonPython 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)[GCC 4.2.1 (Apple Inc. build 5646)] on darwinType "help", "copyright", "credits" or "license"for more information.>>> print "Hello, World!"Hello, World!
  7. 7. “Hello, World!” Start the Python interpreter$ python from the command linePython 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)[GCC 4.2.1 (Apple Inc. build 5646)] on darwinType "help", "copyright", "credits" or "license"for more information.>>> print "Hello, World!"Hello, World!
  8. 8. “Hello, World!”$ pythonPython 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)[GCC 4.2.1 (Apple Inc. build 5646)] on darwinType "help", "copyright", "credits" or "license"for more information.>>> print "Hello, World!"Hello, World! Generic information about the Python interpreter.
  9. 9. “Hello, World!”$ pythonPython 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)[GCC 4.2.1 (Apple Inc. build 5646)] on darwinType "help", "copyright", "credits" or "license"for more information.>>> print "Hello, World!"Hello, World! You type this bit...
  10. 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. 11. “Hello, World!” function def hello(name="World!"): """ Makes Python say hello. :param name: who to greet """ return "Hello, %s" % name
  12. 12. “Hello, World!” functionFunctions 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. 13. “Hello, World!” functiondef = define def hello(name="World!"): """ Makes Python say hello. :param name: who to greet """ return "Hello, %s" % name
  14. 14. “Hello, World!” functionhello = name of function def hello(name="World!"): """ Makes Python say hello. :param name: who to greet """ return "Hello, %s" % name
  15. 15. “Hello, World!” functionan argument (input) into the function def hello(name="World!"): """ Makes Python say hello. :param name: who to greet """ return "Hello, %s" % name
  16. 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. 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. 18. “Hello, World!” function def hello(name="World!"): """ Makes Python say hello.comments & docs :param name: who to greet """ return "Hello, %s" % name
  19. 19. “Hello, World!” function def hello(name="World!"): """ Makes Python say hello. :param name: who to greet """ return "Hello, %s" % name return = result
  20. 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. 21. “Hello, World!” function def hello(name="World!"): """ Makes Python say hello. :param name: who to greet """ return "Hello, %s" % name string formatting
  22. 22. Call the function (note the brackets)>>> hello()Hello, World!>>> hello("NortHACKton")Hello, NortHACKton>>> hello("Widget")Hello, Widget
  23. 23. >>> hello() Here’s the result...Hello, World!>>> hello("NortHACKton")Hello, NortHACKton>>> hello("Widget")Hello, Widget
  24. 24. >>> hello() Hello, World! >>> hello("NortHACKton") Hello, NortHACKton >>> hello("Widget") Hello, WidgetAha! Pass in arguments between the brackets...
  25. 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. 26. HELP!>>> dir() return the attributes of given scope[__builtins__, __doc__,__name__, __package__, hello]>>> help(hello) display help from docstringHelp on function hello in module __main__:hello(name=World!) Makes Python say hello. :param name: who to greet
  27. 27. Assignment>>> greeting = hello(NortHACKton!)>>> greetingHello, 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. 28. Assignment>>> greeting = hello(NortHACKton!)>>> greeting greeting holds the return valueHello, 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. 29. Assignment>>> greeting = hello(NortHACKton!)>>> greetingHello, 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. 30. Assignment>>> greeting = hello(NortHACKton!)>>> greetingHello, 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. 31. Assignment>>> greeting = hello(NortHACKton!)>>> greetingHello, 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. 32. Assignment>>> greeting = hello(NortHACKton!)>>> greetingHello, 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. 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. 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. 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 roundNB: there is NO switch in Python. Use elif for further clauses in the logic.
  36. 36. Loops>>> for number in range(10):... print number... Basically, for each “something” in agroup of “somethings” do something (for each number in a group of numbers print the number)
  37. 37. Loops>>> for number in range(10):... print number...0123 Like many programming languages,4 Python starts counting from 0 (zero)56789 There’s also while
  38. 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. 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 positionparrot>>> 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. 40. Modulesimport antigravityfrom antigravity import stasisfieldstasisfield.generate()
  41. 41. OOP(s)
  42. 42. In a nutshell (there’s much more to it than this) Classes define sorts of thingsObjects are instances of classes
  43. 43. Cow = classButtercup = object (an instance of cow)
  44. 44. In a nutshell (part 2) (there’s still much more to it than this)Methods do things (they’re functions) Attributes define, er, attributes...
  45. 45. Moo! Buttercup.moo() Buttercup.breed = “friesian”
  46. 46. A very simple view... Nouns = Classes Proper Nouns = Objects Verbs = Methods Adjectives = Attributeser, sort of... I’m making this up as I go along... :-)
  47. 47. 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)
  48. 48. 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)
  49. 49. ... 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)
  50. 50. ... 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)
  51. 51. 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)
  52. 52. 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 = breedcalled 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
  53. 53. 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)
  54. 54. 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)
  55. 55. 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 theobject dosomething
  56. 56. >>> from example import Cow>>> buttercup = cow("Buttercup", "friesian")>>> buttercup.nameButtercup>>> buttercup.breedfriesian>>> buttercup.moo()Buttercup says, MOO!
  57. 57. http://docs.python.org/tutorial/introduction.html
  58. 58. and now for something completely different...
  59. 59. Your task:Create a Parrot class. It must be able to squawk, flap and, ahem, become deceased. If the parrot is deceased thencalling 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!
  60. 60. Show and tell...
  61. 61. End (the)http://python.org/

×