Presentation is loading. Please wait.

Presentation is loading. Please wait.

A Crash Course Python. Python? Isn’t that a snake? Yes, but it is also a...

Similar presentations


Presentation on theme: "A Crash Course Python. Python? Isn’t that a snake? Yes, but it is also a..."— Presentation transcript:

1 A Crash Course Python

2 Python? Isn’t that a snake? Yes, but it is also a...

3 ... general-purpose open source computer programming language, optimized for quality, productivity, portability, and integration. It is used by hundreds of thousands of developers around the world, in areas such as Internet scripting, systems programming, user interfaces, product customization, and more. From Programming Python 2nd Ed.

4 No compile of link steps No type declarations Automatic memory management High-level datatypes and operation Object-oriented programming Embedding and extending in C/C++ Classes, modules, exceptions A simple, clear syntax and design Universal “first-class” object model Interactive, dynamic nature Access to interpreter information Wide interpreter portability Large collection of libraries & tools System calls

5 What does it look like? foo = 10 bar = “foo” foo2, bar2 = foo, bar if x 10 and x < 20): print "The value is OK." if x < 5 or 10 < x < 20: print "The value is OK." for i in [1,2,3,4,5]: print "This is iteration number", i for j in range(5): print “This is iteration number”, j+1 x = 10 while x >= 0: print "x is still not negative." x = x-1

6 Calculator Basics Numbers x,y = 10, 5 z = x + y x,y = 10.2, 4.8 z = x + y x = 10.2 + 4.8j y = complex(10,4) z = x.real a = y.imag

7 Strings u“spam eggs” #unicode d = r‘spam eggs’ #raw l = len(d) “”” spam eggs ””” s = “spam” + “eggs” varSpam = s[0:4]

8 Lists >>> a = ['spam', 'eggs', 100, 1234] >>> a ['spam', 'eggs', 100, 1234] >>> a[0] 'spam' >>> a[3] 1234 >>> a[-2] 100 >>> a[1:-1] ['eggs', 100] >>> a[:2] + ['bacon', 2*2] ['spam', 'eggs', 'bacon', 4] >>> q = [2, 3] >>> p = [1, q, 4] >>> len(p) 3 >>> p[1] [2, 3] >>> p[1][0] 2 >>> p[1].append('xtra') >>> p [1, [2, 3, 'xtra'], 4] >>> q [2, 3, 'xtra']

9 >>>d2 = {‘spam’:2, ‘ham’:1, ‘eggs’:3} >>>d2[‘ham’] 2 >>>len(d2) 3 >>>d2.has_key(‘spam’) 1 >>>d2.keys() [‘spam’,’ham’,’eggs’] >>>del d2[‘ham’] 1 >>>len(d2) 2 Dictionaries In Python false is [ ], 0, “”, None true is everything else

10 Tuples >>> a = ("foo",10,5+6j) >>> a ('foo', 10, (5+6j)) >>> a[0] 'foo‘ >>> del a[1] Traceback (most recent call last): File " ", line 1, in ? TypeError: object doesn't support item deletion >>>

11 Functions def fib(n): # write Fibonacci series up to n """Print a Fibonacci series up to n.""" a, b = 0, 1 while b < n: print b, a, b = b, a+b def foo(n): return lambda x: x+ n

12 Modules - files that have Python functions and statements - can by run as a script or imported -.py extension - module namespace - import sys - from sys import * - __name__ is the name of the module - if running as a script it is ‘__main__’

13 Files import sys #built atop C i/o myFile = open(”file.txt”, ‘r’) # ‘r’ read # ‘w’ write # ‘a’ append a = myFile.readline() #go over a list of strings returned by readlines() for i in myFile.readlines(): sys.stdout.write(i) #tell & seek are also methods #optional if exiting app since GC will close it then myFile.close()

14 Exceptions import string, sys try: f = open('myfile.txt') s = f.readline() i = int(string.strip(s)) except IOError, (errno, strerror): # exception w/ arguments print "I/O error(%s): %s" % (errno, strerror) except ValueError: print "Could not convert data to an integer." except: #default print "Unexpected error:", sys.exc_info()[0] raise #throw finally: pass try: raise NameError, 'HiThere' except NameError: print 'An exception flew by!' raise #User defined exceptions extend the Exception class

15 Classes class Bag: def __init__(self): self.data = [] def add(self, x): self.data.append(x) def addtwice(self, x): self.add(x)

16 Boost.python Following C/C++ tradition, let's start with the "hello, world". A C++ Function: char const *greet () {return "hello, world" ;} can be exposed to Python by writing a Boost.Python wrapper: #include using namespace boost::python ; BOOST_PYTHON_MODULE (hello ){ def ("greet",greet ); } That's it. We're done. We can now build this as a shared library. The resulting DLL is now visible to Python. Here's a sample Python session: >>> import hello >>> print hello.greet() hello,world

17 Jython C:\jython>jython Jython 2.0 on java1.2.1 Type "copyright", "credits" or "license" for more information. >>> from java.util import Random >>> r = Random() >>> r.nextInt() -790940041 >>> for i in range(5):... print r.nextDouble()... 0.23347681506123852 0.8526595592189546 0.3647833839988137 0.3384865260567278 0.5514469740469587 >>>

18 References Lutz, Mark. Programming Python, 2nd Ed. (Safari online through UW Libraries) Lutz, Mark & Ascher, David. Learning Python (In ACM Library in 326) www.jython.org www.python.org http://www.boost.org/libs/python/doc/index.htm l


Download ppt "A Crash Course Python. Python? Isn’t that a snake? Yes, but it is also a..."

Similar presentations


Ads by Google