import this
The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!
#Variable type is inferred in python ("Duck Typing")
my_int = 3
my_string = "foo"
print "Type of my_int:", type(my_int)
print "Type of my_string:", type(my_string)
Type of my_int: <type 'int'> Type of my_string: <type 'str'>
#Python operators can mean different things for different types
print my_int*3
print my_string*3
9 foofoofoo
#In python, we don't need {}, ;, and indentation matters
if my_int > 0:
print my_int, "is positive"
else:
print "Uh-oh"
print "And now we are back!"
3 is positive And now we are back!
#Python reads like english, so boolean operations are just words
print True and False
print True or False
print not True
False True False
#Functions in python are familiar, but because python is duck-typed,
#we don't have return type
def is_even(number):
return (number % 2) == 0
print 'is 3 even?', is_even(3)
print 'is 100 even?', is_even(100)
is 3 even? False is 100 even? True
#Even though type is inferred, python is strongly-typed: certain
#operations are forbidden
print "1"+1
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-7-8c21401950b3> in <module>() 1 #Even though type is inferred, python is strongly-typed: certain 2 #operations are forbidden ----> 3 print "1"+1 TypeError: cannot concatenate 'str' and 'int' objects
#Python is object-oriented: Every variable is an object,
#and objects can have methods
alist = [1,2,3]
print alist
alist.reverse()
print alist
[1, 2, 3] [3, 2, 1]
#This is how the operator overloading works
print dir(alist)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
#Define an array
a = [1,2,3,4]
#Print the first & last element
print a[0], a[-1]
1 4
#Add some more elements to the list
a = a + [5,6,7]
print a
[1, 2, 3, 4, 5, 6, 7]
#Get a subset of the list
print a[2:5]
[3, 4, 5]
#Find the length of a list
print len(a)
7
#Print every second element
print a[0:-1:2]
[1, 3, 5]
#2D Arrays are easy too
b = [a,a,a]
print b
print b[1]
print b[2][3]
[[1, 2, 3, 4, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7]] [1, 2, 3, 4, 5, 6, 7] 4
#Dicts are a kind of datastructure called a Hash Table
codon = {'UUU':'Phenylalanine', 'CUU':'Isoleucine', 'GGU':'Glycine', 'AGU':'Serine'}
#Lookup in a dict runs in constant time
print 'UUU encodes ', codon['UUU']
#Dicts have keys & Values
print 'The Keys are:', codon.keys()
print 'The Values are:', codon.values()
UUU encodes Phenylalanine The Keys are: ['UUU', 'GGU', 'CUU', 'AGU'] The Values are: ['Phenylalanine', 'Glycine', 'Isoleucine', 'Serine']
#Rather than build a list with a loop, you can use a list-comprehension
squares = []
for i in range(10):
squares.append(i*i)
print "With a loop", squares
squares = [i*i for i in range(10)]
print "With a comprehension", squares
With a loop [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] With a comprehension [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
#Dicts also have comprehensions
cubes = {i:i*i*i for i in range(10)}
print cubes.keys()
print cubes.values()
print "3 cubed is", cubes[3]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 1, 8, 27, 64, 125, 216, 343, 512, 729] 3 cubed is 27
#Python function arguments each have a name, but they
#can also be assigned a default value
def get_last(inlist, num=1):
return inlist[-num:]
print get_last([1,2,3,4])
print get_last([1,2,3,4], 2)
print get_last(inlist=[1,2,3,4])
print get_last(inlist=[1,2,3,4], num=3)
[4] [3, 4] [4] [2, 3, 4]
from matplotlib.pyplot import *
from numpy import *
xvals = arange(0,2*pi,1e-3)
yvals = sin(xvals)
plot(xvals,yvals)
xlabel('x')
ylabel('sin(x)')
<matplotlib.text.Text at 0x7fbaf016f750>
#Let's test the central limit theorem
randnums = [mean(random_integers(0,10,1000)) for i in range(10000)]
null = hist(randnums,bins=50)
#Even 3d plots work nicely
from mpl_toolkits.mplot3d import axes3d
ax = gcf().add_subplot(111, projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
ax.plot_wireframe(X,Y,Z, rstride=10, cstride=10)
<mpl_toolkits.mplot3d.art3d.Line3DCollection at 0x7fbaefe0eb10>