Stochastic Technologies Available As A Short Ebook
Stochastic Technologies Available As A Short Ebook
NOTE: If you would like some Python development done, my company, Stochastic Technologies, is available for consulting. Also, this tutorial is available as a short ebook.
Preliminary fluff
So, you want to learn the Python programming language but can't find a concise and yet fullfeatured tutorial. This tutorial will attempt to teach you Python in 10 minutes. It's probably not so much a tutorial as it is a cross between a tutorial and a cheatsheet, so it will just show you some basic concepts to start you off. Obviously, if you want to really learn a language you need to program in it for a while. I will assume that you are already familiar with programming and will, therefore, skip most of the non-language-specific stuff. The important keywords will be highlighted so you can easily spot them. Also, pay attention because, due to the terseness of this tutorial, some things will be introduced directly in code and only briefly commented on.
Properties
Python is strongly typed (i.e. types are enforced), dynamically, implicitly typed (i.e. you don't have to declare variables), case sensitive (i.e. var and VAR are two different variables) and object-oriented (i.e. everything is an object).
Getting help
Help in Python is always available right in the interpreter. If you want to know how an object works, all you have to do is call help(<object>)! Also useful are dir(), which shows you all the object's methods, and <object>.__doc__, which shows you its documentation string: ? 1 >>> help(5) 2 Help on int object: 3 (etc etc) 4 5 >>> dir(5) 6 ['__abs__', '__add__', ...] 7 8 >>> abs.__doc__ 'abs(number) -> number 9 10Return the absolute value of the argument.' 11
Syntax
Python has no mandatory statement termination characters and blocks are specified by indentation. Indent to begin a block, dedent to end one. Statements that expect an indentation level end in a colon (:). Comments start with the pound (#) sign and are single-line, multi-line strings are used for multi-line comments. Values are assigned (in fact, objects are bound to names) with the _equals_ sign ("="), and equality testing is done using two _equals_ signs ("=="). You can increment/decrement values using the += and -= operators respectively by the right-hand amount. This works on many datatypes, strings included. You can also use multiple variables on one line. For example: ? 1 2 >>> myvar = 3 3 >>> myvar += 2 4 >>> myvar 5 5 6 >>> myvar -= 1 >>> myvar 7 4 8 """This is a multiline comment. 9 The following lines concatenate the two strings.""" 10>>> mystring = "Hello" 11>>> mystring += " world." >>> print mystring 12Hello world. 13# This swaps the variables in one line(!). 14# It doesn't violate strong typing because values aren't 15# actually being assigned, but new objects are bound to 16# the old names. >>> myvar, mystring = mystring, myvar 17 18
Data types
The data structures available in python are lists, tuples and dictionaries. Sets are available in the sets library (but are built-in in Python 2.5 and later). Lists are like one-dimensional arrays (but you can also have lists of other lists), dictionaries are associative arrays (a.k.a. hash tables) and tuples are immutable one-dimensional arrays (Python "arrays" can be of any type, so you can mix e.g. integers, strings, etc in lists/dictionaries/tuples). The index of the first item in all array types is 0. Negative numbers count from the end towards the beginning, -1 is the last item. Variables can point to functions. The usage is as follows: ? 1 2 3
>>> >>> >>> >>> sample = [1, ["another", "list"], ("a", "tuple")] mylist = ["List item 1", 2, 3.14] mylist[0] = "List item 1 again" mylist[-1] = 3.14
mydict = {"Key 1": "Value 1", 2: 3, "pi": 3.14} mydict["pi"] = 3.15 mytuple = (1, 2, 3) myfunction = len print myfunction(mylist)
You can access array ranges using a colon (:). Leaving the start index empty assumes the first item, leaving the end index assumes the last item. Negative indexes count from the last item backwards (thus -1 is the last item) like so: ? 1 2>>> mylist = ["List item 1", 2, 3.14] >>> print mylist[:] 3['List item 1', 2, 3.1400000000000001] 4>>> print mylist[0:2] 5['List item 1', 2] 6>>> print mylist[-3:-1] 7['List item 1', 2] >>> print mylist[1:] 8[2, 3.14] 9
Strings
Its strings can use either single or double quotation marks, and you can have quotation marks of one kind inside a string that uses the other kind (i.e. "He said 'hello'." is valid). Multiline strings are enclosed in _triple double (or single) quotes_ ("""). Python supports Unicode out of the box, using the syntax u"This is a unicode string". To fill a string with values, you use the % (modulo) operator and a tuple. Each %s gets replaced with an item from the tuple, left to right, and you can also use dictionary substitutions, like so: ? 1 >>>print "Name: %s\ 2 Number: %s\ 3 String: %s" % (myclass.name, 3, 3 * "-") 4 Name: Poromenos 5 Number: 3 String: --6 7 strString = """This is 8 a multiline 9 string.""" 10 11# WARNING: Watch out for the trailing s in "%(key)s". "This 12>>> print test. %(verb)s a %(noun)s." % {"noun": "test", "verb": "is"} This is a 13
14
Functions
Functions are declared with the "def" keyword. Optional arguments are set in the function declaration after the mandatory arguments by being assigned a default value. For named arguments, the name of the argument is assigned a value. Functions can return a tuple (and using tuple unpacking you can effectively return multiple values). Lambda functions are ad hoc
functions that are comprised of a single statement. Parameters are passed by reference, but immutable types (tuples, ints, strings, etc) *cannot be changed*. This is because only the memory location of the item is passed, and binding another object to a variable discards the old one, so immutable types are replaced. For example: ? 1 2 # Same as def f(x): return x + 1 3 functionvar = lambda x: x + 1 4 >>> print functionvar(1) 5 2 6 7 # an_int and a_string are optional, they have default values # if one is not passed (2 and "A default string", respectively). 8 def passing_example(a_list, an_int=2, a_string="A default string"): 9 a_list.append("A new item") 10 an_int = 4 return a_list, an_int, a_string 11 12 13>>> my_list = [1, 2, 3] >>> my_int = 10 14>>> print passing_example(my_list, my_int) 15([1, 2, 3, 'A new item'], 4, "A default string") 16>>> my_list 17[1, 2, 3, 'A new item'] 18>>> my_int 10 19 20
Classes
Python supports a limited form of multiple inheritance in classes. Private variables and methods can be declared (by convention, this is not enforced by the language) by adding at least two leading underscores and at most one trailing one (e.g. "__spam"). We can also bind arbitrary names to class instances. An example follows: ? 1 class MyClass: common = 10 2 def __init__(self): 3 self.myvariable = 3 4 def myfunction(self, arg1, arg2): 5 return self.myvariable 6 # This is the class instantiation 7 >>> classinstance = MyClass() 8 >>> classinstance.myfunction(1, 2) 9 3 10# This variable is shared by all classes. 11>>> classinstance2 = MyClass()
12>>> classinstance.common 1310 >>> classinstance2.common 1410 15# Note how we use the class name 16# instead of the instance. 17>>> MyClass.common = 30 18>>> classinstance.common 30 19>>> classinstance2.common 2030 21# This will not update the variable on the class, 22# instead it will bind a new object to the old # variable name. 23>>> classinstance.common = 10 24>>> classinstance.common 2510 26>>> classinstance2.common 2730 >>> MyClass.common = 50 28# This has not changed, because "common" is 29# now an instance variable. 30>>> classinstance.common 3110 >>> classinstance2.common 3250 33 34# This class inherits from MyClass. Multiple 35# inheritance is declared as: 36# class OtherClass(MyClass1, MyClass2, MyClassN) 37class OtherClass(MyClass): # The "self" argument is passed automatically 38 # and refers to the class instance, so you can set 39 # instance variables as above, but from inside the class. def __init__(self, arg1): 40 self.myvariable = 3 41 print arg1 42 43>>> classinstance = OtherClass("hello") 44hello 45>>> classinstance.myfunction(1, 2) 463 47# This class doesn't have a .test member, but # we can add one to the instance anyway. Note 48# that this will only be a member of classinstance. 49>>> classinstance.test = 10 50>>> classinstance.test 5110 52 53 54 55 56 57
58 59 60 61
Exceptions
Exceptions in Python are handled with try-except [exceptionname] blocks: ? 1 2 def some_function(): 3 try: # Division by zero raises an exception 4 10 / 0 5 except ZeroDivisionError: 6 print "Oops, invalid." 7 else: 8 # Exception didn't occur, we're good. pass 9 finally: 10 # This is executed after the code block is run 11 # and all exceptions have been handled, even 12 # if a new exception is raised while handling. 13 print "We're done with that." 14 15>>> some_function() 16Oops, invalid. We're done with that. 17 18
Importing
External libraries are used with the import [libname] keyword. You can also use from [libname] import [funcname] for individual functions. Here is an example: ? 1import random 2from time import clock 3 4randomint = random.randint(1, 100) 5>>> print randomint 64 6
File I/O
Python has a wide array of libraries built in. As an example, here is how serializing (converting data structures to strings using the pickle library) with file I/O is used: ? 1 2 3 import pickle mylist = ["This", "is", 4, 13327] 4 # Open the file C:\\binary.dat for writing. The letter r before the 5 # filename string is used to prevent backslash escaping. 6 myfile = file(r"C:\\binary.dat", "w") 7 pickle.dump(mylist, myfile) myfile.close() 8 9 myfile = file(r"C:\\text.txt", "w") 10myfile.write("This is a sample string") 11myfile.close() 12 13myfile = file(r"C:\\text.txt") 14>>> print myfile.read() 'This is a sample string' 15myfile.close() 16 17# Open the file for reading. 18myfile = file(r"C:\\binary.dat") 19loadedlist = pickle.load(myfile) 20myfile.close() >>> print loadedlist 21['This', 'is', 4, 13327] 22 23