1. One line to make it import able if __name__ == '__main__' : Test()
2.
3. by Marilyn Davis, Ph.D. [email_address] Marakana Open Source Training www.marakana.com Why Python?
4.
5. """pig.py 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 "way" 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 "ay". """ def Pigify (word): """Return the word translated to piglatin.""" vowels = "aeiouyAEIOUY" if word[0] in vowels: return word + 'way' # concatonation
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 "ay". """ def Pigify (word): """Return the word translated to piglatin.""" # code blocks are delimited by indentation vowels = "aeiouyAEIOUY" 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. def Test (): """Test a few words.""" for word in "chocolate" , "nuts" , "cherry" : # comma suppresses the new line print Pigify(word), print # just prints a new line Test() “”” OUTPUT: $ pig.py ocolatechay utsnay errychay $ """
8. $ pig.py ocolatechay utsnay errychay $ #!/usr/bin/env python (Top line in unix)
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 ( "radius: " ) answer = GetCircleAttributes(radius) if answer: circumference, area = answer print "Circumference =" , circumference print "Area =" , area else : print "That wasn't a number!"
10. A Program File is a Module is a Namespace __main__ The module being run is “__main__” ( magic main ).
11. Each object in the module is another namespace Function Object str Object float Object __main__
12. Each import brings a neighboring namespace into your code. math __main__
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 "help", "copyright", "credits" or "license" for more information. >>> dir() ['__builtins__', '__doc__', '__name__', '__package__'] >>> __name__ '__main__' >>> a_string = "Hi" >>> dir() ['__builtins__', '__doc__', '__name__', '__package__', 'a_string']
18. >>> help(pig) Help on module pig: NAME pig FILE /home/marilyn/python/Why_Python/pig.py DESCRIPTION pig.py 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 "way" to the end of the word.
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 "ay". FUNCTIONS Pigify(word) Return the word translated to piglatin. Test() Test a few words. >>> pig.Pigify("jalapenos") 'alapenosjay'
20. import pig def PigLatin(): """Prompts for English, prints pig latin. """ line = raw_input ( “Tell me something good: “ ) for word in line.split(): print pig.Pigify(word), print PigLatin()
27. More Iterating file_obj = open ( "ram_tzu" ) for line in file_obj: print line, """ Ram Tzu knows this: When God wants you to do something, You think it's your idea. """
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. Regular expressions plus r"a string” 'r' prepended to a string makes a raw string The backslashes are literal. import re p = re.compile( r”(( ?P<first> +) ?( ?P<middle> ??)) Jones”) m = p.search("John J. Jones") >>> m.groups(2) 'John' >>> m.group('first') 'John' Named groups!
33. String formatting plus >>> print "The %s eats some %s before %s time." % (a_dict["animal"], a_dict["food"], a_dict["hobby"]) The cat eats some cheese before sleeping time. Dictionary Replacement >>> print "The %(animal)s eats some %(food)s before %(hobby)s time." % a_dict The cat eats some cheese before sleeping time.
37. OS Module >>> import os >>> os.linesep '' '' >>> os.path.join("some", "path") 'some/path' 'somepath' >>> Linux Windows
38.
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. 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.
42.
43. An empirical comparison of C, C++, Java, Perl, Python, Rexx, and Tcl for a search/string-processing program Lutz Prechelt (prechelt@ira.uka.de) Fakultat fur Informatik Universitat Karlsruhe D-76128 Karlsruhe, Germany March 10, 2000 page.mi.fu-berlin.de/~prechelt/Biblio/jccpprtTR.pdf
56. Python Programmers Have less to do when it's time to modify and enhance the code. Python code is easy to read.
57.
58.
59.
60.
61.
62.
63. "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," ... Hilmar Veigar Petursson of CCP Games.
64. Python has provided us with a measurable productivity gain that allows us to stay competitive in the online travel space," said Michael Engelhart, CTO of EZTrip.com .
65. “ Python is of tremendous value throughout an embedded system's lifecycle.” ..Thomas Major, Product Development Manager Carmanah LED lighting and solar photovoltaic systems
66.
67.
68.
69. "Python is fast enough for our site and allows us to produce maintainable features in record times, with a minimum of developers," Cuong Do, Software Architect, YouTube.com.
70.
71.
72.
73.
74.
75.
76.
77. The point of a programming language is to communicate with other engineers in a language that also the computer understands.