Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Why Python by Marilyn Davis, Marakana


Published on

Marilyn Davis on Why Python at Marakana

Published in: Technology
  • Be the first to comment

Why Python by Marilyn Davis, Marakana

  1. 1. One line to make it import able if __name__ == '__main__' : Test()
  2. 2. Desirable Attributes for Programs <ul><li>Programmer Friendly </li></ul><ul><li>Correct </li></ul><ul><li>Efficient </li></ul><ul><li>Portable? </li></ul>
  3. 3. by Marilyn Davis, Ph.D. [email_address] Marakana Open Source Training Why Python?
  4. 4. Programmer Friendly <ul><li>Pleasant to look at. </li></ul><ul><li>Easy to read and modify. </li></ul><ul><li>Manages complication. </li></ul><ul><li>Invites collaboration. </li></ul>
  5. 5. &quot;&quot;&quot; word [word2 ...] Prints the word(s) in Pig Latin. The rules for forming Pig Latin words are: o If the word begins with a vowel, add &quot;way&quot; to the end of the word. o If the word begins with a consonant, extract consonants up to the first vowel, move those consonants to the end of the word, and add &quot;ay&quot;. &quot;&quot;&quot; def Pigify (word): &quot;&quot;&quot;Return the word translated to piglatin.&quot;&quot;&quot; vowels = &quot;aeiouyAEIOUY&quot; if word[0] in vowels: return word + 'way' # concatonation
  6. 6. o If the word begins with a consonant, extract consonants up to the first vowel, move those consonants to the end of the word, and add &quot;ay&quot;. &quot;&quot;&quot; def Pigify (word): &quot;&quot;&quot;Return the word translated to piglatin.&quot;&quot;&quot; # code blocks are delimited by indentation vowels = &quot;aeiouyAEIOUY&quot; if word[0] in vowels: return word + 'way' # concatonation # loop through a sequence, with index for i, char in enumerate (word): if char in vowels: break return word[i:] + word[:i] + 'ay' # slicing
  7. 7. def Test (): &quot;&quot;&quot;Test a few words.&quot;&quot;&quot; for word in &quot;chocolate&quot; , &quot;nuts&quot; , &quot;cherry&quot; : # comma suppresses the new line print Pigify(word), print # just prints a new line Test() “”” OUTPUT: $ ocolatechay utsnay errychay $ &quot;&quot;&quot;
  8. 8. $ ocolatechay utsnay errychay $ #!/usr/bin/env python (Top line in unix)
  9. 9. import math def GetCircleAttributes (radius): try : radius = float(radius) except ValueError : return None circumference = math.pi * 2 * radius area = math.pi * radius * radius return circumference, area radius = raw_input ( &quot;radius: &quot; ) answer = GetCircleAttributes(radius) if answer: circumference, area = answer print &quot;Circumference =&quot; , circumference print &quot;Area =&quot; , area else : print &quot;That wasn't a number!&quot;
  10. 10. A Program File is a Module is a Namespace __main__ The module being run is “__main__” ( magic main ).
  11. 11. Each object in the module is another namespace Function Object str Object float Object __main__
  12. 12. Each import brings a neighboring namespace into your code. math __main__
  13. 13. Introspection $ python Python 2.6 (r26:66714, Dec 31 2008, 14:19:00) [GCC 4.2.4 (Ubuntu 4.2.4-1ubuntu3)] on linux2 Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information. >>> dir() ['__builtins__', '__doc__', '__name__', '__package__'] >>> __name__ '__main__' >>> a_string = &quot;Hi&quot; >>> dir() ['__builtins__', '__doc__', '__name__', '__package__', 'a_string']
  14. 14. >>> dir(a_string) ['__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']
  15. 15. >>> a_string.swapcase() 'hI' The dot operator travels into a Namespace.
  16. 16. >>> import math >>> dir() ['__builtins__', '__doc__', '__name__', '__package__', 'a_string', 'math'] >>> dir(math) ['__doc__', '__file__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'hypot', 'isinf', 'isnan', 'ldexp', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
  17. 17. >>> import pig >>> dir() ['__builtins__', '__doc__', '__name__', '__package__', 'a_string', math', 'pig'] >>> dir(pig) ['Pigify', 'Test', '__builtins__', '__doc__', '__file__', '__name__', '__package__'] >>>
  18. 18. >>> help(pig) Help on module pig: NAME pig FILE /home/marilyn/python/Why_Python/ DESCRIPTION word [word2 ...] Prints the word(s) in Pig Latin. The rules for forming Pig Latin words are: o If the word begins with a vowel, add &quot;way&quot; to the end of the word.
  19. 19. o If the word begins with a consonant, extract consonants up to the first vowel, move those consonants to the end of the word, and add &quot;ay&quot;. FUNCTIONS Pigify(word) Return the word translated to piglatin. Test() Test a few words. >>> pig.Pigify(&quot;jalapenos&quot;) 'alapenosjay'
  20. 20. import pig def PigLatin(): &quot;&quot;&quot;Prompts for English, prints pig latin. &quot;&quot;&quot; line = raw_input ( “Tell me something good: “ ) for word in line.split(): print pig.Pigify(word), print PigLatin()
  21. 21. Pythonic Thinking object . attribute Namespaces! menu.lunch.salad = 'caesar'
  22. 22. Object-Oriented Programming
  23. 23. A class is: <ul><li>A blueprint for a namespace. </li></ul>An object is: <ul><ul><li>A namespace constructed from the blueprint. </li></ul></ul>
  24. 24. class Rock: def SetType ( self , rock_type): self.type = rock_type def __str__ ( self ): return &quot;Rock object: &quot; + self.type rock_object = Rock() rock_object.SetType( &quot;Pet&quot; ) print rock_object &quot;&quot;&quot; OUTPUT: Rock object: Pet &quot;&quot;&quot;
  25. 25. >>> a_list = [3, 8, 1] >>> a_list[1] = 88 >>> a_list.pop() 1 >>> a_list [3, 88] Data Structures (types) Lists
  26. 26. >>> a_dict = {} >>> a_dict[&quot;Mary&quot;] = &quot;678-8823&quot; >>> a_dict[&quot;Zoe&quot;] = &quot;555-1234&quot; >>> a_dict[3] = &quot;12&quot; >>> a_dict {3: '12', 'Mary': '678-8823','Zoe':'555-1234'} >>> for each_key in a_dict: ... print each_key, a_dict[each_key] ... 3 12 Mary 678-8823 Zoe 555-1234 >>> Dictionaries (hash table, associative array)
  27. 27. More Iterating file_obj = open ( &quot;ram_tzu&quot; ) for line in file_obj: print line, &quot;&quot;&quot; Ram Tzu knows this: When God wants you to do something, You think it's your idea. &quot;&quot;&quot;
  28. 28. Swapping this = 1 that = 100 this, that = that, this
  29. 29. def GoToThePark (name, best_friend= &quot;Jose&quot; ): print name, 'and' , best_friend print 'go to the park' print 'play hide-and-seek' print 'till long after dark' print GoToThePark( 'Charlie' , 'Jacqueline' ) GoToThePark( 'Judi' ) Default Arguments
  30. 30. Keyword Arguments def Greet (first, last): print 'Hello' , first, last Greet( 'Rocky' , 'The Squirrel' ) Greet(last= 'Moose' , first= 'Bullwinkle' )
  31. 31. >>> [(x, x**2) for x in range(1, 10, 2)] [(1, 1), (3, 9), (5, 25), (7, 49), (9, 81)] >>> reduce(lambda x,y: x + y, range(1,11)) 55 >>> Functional Programming
  32. 32. Regular expressions plus r&quot;a string” 'r' prepended to a string makes a raw string The backslashes are literal. import re p = re.compile( r”(( ?P<first> w+) ?( ?P<middle> w?.?)) Jones”) m =;John J. Jones&quot;) >>> m.groups(2) 'John' >>>'first') 'John' Named groups!
  33. 33. String formatting plus >>> print &quot;The %s eats some %s before %s time.&quot; % (a_dict[&quot;animal&quot;], a_dict[&quot;food&quot;], a_dict[&quot;hobby&quot;]) The cat eats some cheese before sleeping time. Dictionary Replacement >>> print &quot;The %(animal)s eats some %(food)s before %(hobby)s time.&quot; % a_dict The cat eats some cheese before sleeping time.
  34. 34.
  35. 35. Programmer Friendly <ul><li>Pleasant to look at. </li></ul><ul><li>Easy to read and modify. </li></ul><ul><li>Manages complication. </li></ul><ul><li>Invites collaboration. </li></ul>
  36. 36. Desirable Attributes for Programs <ul><li>Programmer Friendly </li></ul><ul><li>Correct </li></ul><ul><li>Efficient </li></ul><ul><li>Portable? </li></ul>
  37. 37. OS Module >>> import os >>> os.linesep ' ' ' ' >>> os.path.join(&quot;some&quot;, &quot;path&quot;) 'some/path' 'someath' >>> Linux Windows
  38. 38. Runs on: <ul><li>Linux/Unix </li></ul><ul><li>Mac </li></ul><ul><li>Windows </li></ul><ul><li>OS/2 </li></ul><ul><li>Amiga </li></ul><ul><li>Nokia Series 60 cell phones </li></ul><ul><li>Any OS with a C compiler! </li></ul>The same source code will run unchanged across all implementations.
  39. 39. Python can integrate with COM, .NET, and CORBA objects. Python is also supported for the Internet Communications Engine (ICE) and many other integration technologies.
  40. 40. SWIG/Boost C/C++ wrapping tools to bring C/C++ libraries into the Python interpreter so you can import myCstuff . Jython For seamless integration of Java libraries on JVM. IronPython Microsoft's implementation for .NET. You can also go the opposite route and embed Python in your own application.
  41. 41. Desirable Attributes for Programs <ul><li>Programmer Friendly </li></ul><ul><li>Correct </li></ul><ul><li>Efficient </li></ul><ul><li>Portable? </li></ul>
  42. 42. Correct <ul><li>The easier it is to read the code, and the more the language handles the tedious details, like data-typing, memory management, and loop set-up, the easier it is to make the program correct. </li></ul>
  43. 43. An empirical comparison of C, C++, Java, Perl, Python, Rexx, and Tcl for a search/string-processing program Lutz Prechelt ( Fakultat fur Informatik Universitat Karlsruhe D-76128 Karlsruhe, Germany March 10, 2000
  44. 45. Efficient <ul><li>Quick to write. </li></ul><ul><li>Efficient at run time. </li></ul><ul><ul><li>Fast-running. </li></ul></ul><ul><ul><li>Conserves memory. </li></ul></ul>
  45. 48. http://www.osnews.comstory.php?news_id=5602&page=3 Speed /
  46. 49. http://scutigena. sourceforge .net/
  47. 50.
  48. 51. What about execution speed ? <ul><li>Modern hardware processors generally make language speed a non-issue. </li></ul><ul><li>Most applications are limited by speed of database or network connection, not programming language. </li></ul>Steven Ferg, Bureau of Labor Statistics,
  49. 53. Productivity = Lines of code <ul><li>1 machine instruction for Assembly Language </li></ul><ul><li>3 to 7 machine instructions for C/C++ and Java </li></ul><ul><li>100 's to 1000 's of instructions for Perl and Python </li></ul>A programmer can produce roughly the same number of lines of code per year regardless of the language. But, one line of code translates to: <ul><ul><li>&quot;Scripting: Higher Level Programming for the 21st Century&quot; </li></ul></ul><ul><ul><li>by John K. Ousterhout IEEE Computer magazine, March 1998 </li></ul></ul>
  50. 54. Productivity = Features implemented = Fun Note: A day when you decrease the number of lines of code while maintaining the same functionality is a very productive day. <ul><li>Your code is readable, modifiable, and extendable. </li></ul><ul><li>The behavior matches the specification. </li></ul>
  51. 55. More Instructions/Line of Code <ul><li>Perl and Python programs do more at run time: </li></ul><ul><ul><li>Dynamic data typing. </li></ul></ul><ul><ul><li>Automatic memory management. </li></ul></ul><ul><ul><li>High level data structure manipulation. </li></ul></ul><ul><li>Perl and Python programmers have less to do at development time. </li></ul><ul><ul><li>No data type declarations. </li></ul></ul><ul><ul><li>No memory management. </li></ul></ul><ul><ul><li>Much data manipulation is built in. </li></ul></ul>
  52. 56. Python Programmers Have less to do when it's time to modify and enhance the code. Python code is easy to read.
  53. 57. Developer Reports <ul><li>I find that I'm able to program about three times faster in Python than I could in Java, and three times faster in Java than I could in C. </li></ul><ul><ul><ul><ul><li>Andy Hertzfeld </li></ul></ul></ul></ul>
  54. 58. <ul><li>When a 20,000 line project went to approximately 3,000 lines overnight, and came out being more flexible and robust ... I realized I was on to something really good. </li></ul><ul><ul><ul><ul><li>-- Matthew &quot;Glyph&quot; Lefkowitz </li></ul></ul></ul></ul>
  55. 59. <ul><li>...the lines of Python code were 10% of the equivalent C++ code. </li></ul><ul><ul><ul><ul><li>-- Greg Stein, Google </li></ul></ul></ul></ul>
  56. 60. Who is using Python? What are they doing with it? <ul><li>Industrial Light and Magic: “Every CG image we create has involved Python somewhere in the process,&quot; ...Philip Peterson, Principal Engineer, Research & Development </li></ul>
  57. 61. <ul><li>Disney Feature Length Animation uses Python for its animation production applications. </li></ul>
  58. 62. <ul><li>&quot;Python has been an important part of Google since the beginning, and remains so as the system grows and evolves.” ..Peter Norvig, Director of Search Quality </li></ul>
  59. 63. &quot;Python enabled us to create EVE Online, a massive multiplayer game, in record time. The EVE Online server cluster runs over 25,000 simultaneous players in a shared space simulation, most of which is created in Python. The flexibilities of Python have enabled us to quickly improve the game experience based on player feedback,&quot; ... Hilmar Veigar Petursson of CCP Games.
  60. 64. Python has provided us with a measurable productivity gain that allows us to stay competitive in the online travel space,&quot; said Michael Engelhart, CTO of .
  61. 65. “ Python is of tremendous value throughout an embedded system's lifecycle.” ..Thomas Major, Product Development Manager Carmanah LED lighting and solar photovoltaic systems
  62. 66. <ul><li>Yahoo uses Python for its groups site, and in its Inktomi search engine. </li></ul>
  63. 67. <ul><li>The Philips (formerly IBM ) Fishkill semiconductor manufacturing facility uses Linux and Python for factory tool control. </li></ul>
  64. 68. <ul><li>NASA “Python has met or exceeded every requirement we've had&quot; ... Steve Waterbury, Software Group Leader, NASA STEP Testbed </li></ul>
  65. 69. &quot;Python is fast enough for our site and allows us to produce maintainable features in record times, with a minimum of developers,&quot; Cuong Do, Software Architect,
  66. 70. <ul><li>The National Institute of Health </li></ul><ul><li>and </li></ul><ul><li>Case Western Reserve University are building cutting-edge genetic analysis software with Python. . </li></ul>
  67. 71. <ul><li>The National Weather Service uses Python to prepare weather forecasts. </li></ul>
  68. 72. <ul><li>Lawrence Livermore National Laboratories is basing a new numerical engineering environment on Python. </li></ul>
  69. 73. <ul><li>The Theoretical Physics Division at Los Alamos National Laboratory uses Python to control large-scale simulations on massively parallel supercomputers. </li></ul>
  70. 74. <ul><li>US Navy uses Python & Zope for a web based workflow system. </li></ul>Rear Admiral Grace Murray Hopper
  71. 75. <ul><li>US Department of Agriculture uses Python & Zope for massive collaboration </li></ul>
  72. 76. <ul><li>US Department of Labor uses Python & Zope for the Workforce Connections learning management system. </li></ul>
  73. 77. The point of a programming language is to communicate with other engineers in a language that also the computer understands.