320 likes | 530 Views
The Python Programming Language. Matt Campbell | Steve Losh. From the Creators….
E N D
The Python Programming Language Matt Campbell | Steve Losh
From the Creators… “The language is named after the BBC show ``Monty Python's Flying Circus'' and has nothing to do with nasty reptiles. Making references to Monty Python skits in documentation is not only allowed, it is encouraged! “
Origins • Created in the early 1990s by Guido van Rossum at Stichting Mathematisch Centrum (CWI ) in the Netherlands • Successor language to ABC • Rossum remains the principle author of the language today
Overview of the Language • Python is an interpreted language • Like Scheme, it is an interactive language • Very high-level data types • Code is very human readable
Extensibility • Python is a very extensible language • You can write modules in C to link python to other binary libraries • You can even link the interpreter itself into an application written in C and use python as an extension or command language for that application
Lexical Aspects • Input Format: • Line oriented • White space is not ignored • Comments: • Denoted by hash mark (#) to end of line • Delimiters: • End of line • Keywords: • Reserved • Names: • Case sensitive • Variable names can consist of letters, numbers, and/or underscores • Underscores sometimes have special meaning, so their use is not highly recommended
Data Types • Scalars: • Integer, Float, Boolean • Aggregate Types • Complex Number, String, List, Dictionary, Tuple, File, Set • Python is not strongly typed • Python does not require declaration of variables before their use
Literals • Integers: 2, 4, -3 • Floats: 2.0e10, 3.5, .03 • Boolean: True, False • Strings: ‘cat’, “cat” • Lists: [12, 3.4, ‘cat’, lambda x: x+3] • Sets: set([12, 3.4, ‘cat’, lambda x: x+3]) • Dictionaries: dict = {‘cat': 2, 6: ‘dog’} • Functions: Can be mapped to names via ‘def’ and ‘lambda’ just as in Scheme. They can be returned by functions, placed in lists, etc. • Files: open('/path/file', ‘r+') • Null: None • ‘_’: holds the most recently returned value
Variable Typing • Variables in Python do not need to be declared as a specific type • Example: • A, B = 3, ‘cat’ • A variable’s type is dynamic, and will changed whenever it is reassigned • Example: • a, b = 1, ‘cat’ • a, b = .3, lambda x: x*x • No such thing as “const” in Python
Quick & Dirty Input >>> x = int(raw_input("Please enter an integer: "))
Slicing • Aggregate slicing syntax is similar to ICON Think of indices as pointing between elements in a list. [ ‘cat’, ‘dog’, 3, 4.5 ] 0 1 2 3 4 >>> animals = [‘cat’, ‘dog’, ‘mouse’, ‘bird’] >>> print animals[0:1] [‘cat’, ‘dog’] >> print animals[1:] [‘dog’, ‘mouse’, ‘bird’] >>> tmp = list(“Shrubbery”) >>> tmp[:1] = tmp[-7:] >>> tmp [‘r’, ’u’, ’b’, ’b’, ’e’, ’r’, ’y’, ’S’, ’h’, ’r’, ’u’, ’b’, ’b’, ’e’, ’r’, ’y’]
Ranges • Python has a range function to easily form lists of integers. >>> range(5) [0, 1, 2, 3, 4] >>> range(2,5) [2, 3, 4] >>> range(0, 10, 2) [0, 2, 4, 6, 8] >>> range(5, 0, -1) [5, 4, 3, 2, 1]
in • The in keyword checks if the given object is contained within the aggregate. >>> p = “cat” >>> j = [‘cat’, ‘dog’] >>> p in j True >>> ‘a’ in p True >>> ‘t’ in p[:2] False
Subroutines • Python supports both procedures and functions • Procedure: • def proc1(): print ‘Hi!’ • Function: • def func1(): return ‘Hi!’
Subroutines (continued) • Python does not support name mangling as in C++ • Anything can be returned from a function, including None and other functions • Recursion is allowed • Python has support for calling subroutines in modules written in C • Parameters are passed by value
Scope • Lexical • Global/local scope • Similar to Scheme • No names need to be declared before use
Lifetime / Actions • Variables are alive as long as they can be referenced, similar to Scheme • Python supports standard arithmetic precedence and association with ()’s • Result type is defined the more descriptive of the operands
Control Structures • if statements work as expected >>> if x < 0: … print ‘Negative’ … elif x == 0: … print ‘Zero’ … else: … print “Positive” …
Control Structures continued • for loops differ from c++ and/or java. They iterate over an aggregate. >>> animals = [‘cat’, ‘dog’, ‘horse’] >>> for x in animals: … print x …
Control Structures Continued • for loops can iterate over multiple lists at the same time >>> questions = ['name', 'quest', 'favorite color'] >>> answers = ['lancelot', 'the holy grail', 'blue'] >>> for q, a in zip (questions, answers): ... print 'What is your %s? It is %s.' % (q, a) ... What is your name? It is lancelot. What is your quest? It is the holy grail. What is your favorite color? It is blue.
Pass • The pass command does nothing.
Functions >>> def fib(n): ... a, b = 0, 1 ... while b < n: ... print b, ... a, b = b, a+b ...
Functions continued >>> def makeIncFunc ( n = 1 ) … return lambda x: x + n … >>> tmp = makeIncFunc() >>> print tmp(3) 4 >>> tmp = makeIncFunc(2) >>> print tmp(3) 5
Default Value Side Effects >>> def f(a, L=[]): … L.append(a) … return L … >>> print f(1) [1] >>> print f(2) [1, 2] >>> print f(3) [1, 2, 3]
Classes • Python implements classes in a similar way to Java and C++ >>> class Complex: ... def __init__(self, realpart, imagpart): ... self.r = realpart ... self.i = imagpart ... >>> x = Complex(3.0, -4.5) >>> x.r, x.i (3.0, -4.5)
Inheritance • “Of course, a language feature would not be worthy of the name ``class'' without supporting inheritance. “ class DerivedClassName(BaseClassName): <statement-1> . . . <statement-N>
Multiple Inheritance! class DerivedClassName(Base1, Base2, Base3): <statement-1> . . . <statement-N>
Odds and Ends class Employee: pass john = Employee() john.name = 'John Doe‘ john.dept = 'computer lab‘ john.salary = 1000
Pickling • Python’s equivalent to Serialization >>> pickle.dump( anyobject, fileopenedforwriting ) >>> objecttoloadto = pickle.load( fileopenedforreading )
What this has to do with Legos • A python library calls Pylnp which allows remote control of your robot through the IR tower import lnp lnp.iwrite('hello') lnp.iread() 'world'