Programming is not only about solving problems at all. It is also about:
General characteristics of Python:
clean and simple language: Easy-to-read and intuitive code, easy-to-learn minimalistic syntax
expressive language: Fewer lines of code, fewer bugs, easier to maintain.
general-purpose language in contrast to e.g. Matlab (numerics), PHP (websites), R (statstics). No need to mix languages for a full application, which gets data from a data base and provides a web service, or is integrated in a web service
Technical details:
dynamically typed: No need to define the type of variables, function arguments or return types.
automatic memory management: No need to explicitly allocate and deallocate memory for variables and data arrays. No memory leak bugs.
interpreted: No need to compile the code. The Python interpreter reads and executes the Python code directly.
The main advantage is ease of programming, minimizing the time required to develop, debug and maintain the code.
Other principles:
More facts:
Python's fields of application:
Global install of Python interpreter, you need root access as super user:
Create a local isolated version of Python. This keeps your laptop clean and avoids version conflicts !
Activate this isolated version as follows, you have to to this after each install before you start using this isolated environment !
Now we install a local version of needed python packages:
In [86]:
print "hello word" # this is a comment
In [88]:
print 3, 4,
print 5
In [92]:
name = raw_input("your name: ") # strange name for input function
print "Hello", name, "!!!"
In [93]:
pi = 3.141
my_name = "uwe schmitt"
In [94]:
type(pi)
Out[94]:
In [95]:
# examples for valid names
a = 123
a_123 = 2
_xyz = 2
In [96]:
aBcD = 4 # uppercase matters
abcd = 5
aBcD == abcd
Out[96]:
In [97]:
1abc = 3
In [98]:
print = 4
In [99]:
this_is_a_long_variable_name = 3
thisIsALongVariableName = 4
In [100]:
# some forbidden variable names:
# id, str, type, input, list, file, ...
# often used solution in python community: add a "_"
id_ = 3
type_ = "int"
print_ = 0
In [101]:
print 32 * (41 + 1) / 7
In [102]:
print 29.0 / 2
In [103]:
print 31 / 7
In [104]:
print 31 // 7
In [105]:
print 31 % 7
In [106]:
print 7 / 0
In [107]:
3**117
Out[107]:
can be used for calculating pi up to many digits: http://www.craig-wood.com/nick/articles/pi-machin/
In [108]:
import math
In [109]:
print math.pi
In [110]:
print math.cos(math.pi * 2.0)
In [111]:
print math.sqrt(121.0)
In [112]:
print math.pow(2, 4)
In [113]:
print 2**4 # alternative to math.pow, preserves type
In [114]:
print dir(math)
In [115]:
help(math.log1p)
In [116]:
from math import sin
print sin(3)
In [117]:
from math import *
In [118]:
import math as m
print m.sin(0)
In [119]:
.25 - .2
Out[119]:
In [120]:
type(1 + 3)
Out[120]:
In [121]:
type(1.0 + 3)
Out[121]:
In [122]:
z = 1 + 0.8j
In [123]:
print z, abs(z), z.imag, z.real, z.conjugate()
In [124]:
print z + z, z * z, z**3
In [125]:
z = 1j
print z*z
In [130]:
math.sin(1j)
In [131]:
import cmath
cmath.sin(1j)
Out[131]:
In [132]:
print 3 == 4
In [133]:
print 3 = 4 # would be valid in C/C++ !!!
In [134]:
print 3 != 4
In [135]:
print 3 >= 4, 3<=4, 3 < 4, 3 > 4
In [136]:
print not not True
In [137]:
print 3 < 4 and 3 >= 4
In [138]:
print 3 < 4 or 3 >= 4
In [139]:
print 6 & 12
In [140]:
print 6 | 12
In [141]:
print "Python"
In [142]:
print 'Python'
In [143]:
print """Python:
programming done easy"""
In [144]:
print '''Python
programming done easy'''
In [145]:
print "'abc' is a string"
In [146]:
print '"abc" is a string'
In [147]:
print """those are strings: "abc" and 'abc'"""
In [148]:
print "abc" == "abc"
In [149]:
print "abc" != "ABC"
In [150]:
print "abc" < "abe"
In [151]:
print "abc" < "abcd"
In [152]:
name = "Monty_Python"
print name[0]
In [153]:
print name[-1]
In [154]:
print name[-2]
In [155]:
print name[-12] == name[0]
In [160]:
"01234"[1:4]
Out[160]:
In [163]:
print "0123456789"[1:8:2]
In [164]:
name = "Monty_Python"
print name[:7]
In [165]:
print name[7:]
In [169]:
print name[3:-2:2]
In [170]:
print name[-2:3:-2]
In [171]:
print name[:]
In [172]:
len(name[3:7]) == 7 - 3
Out[172]:
In [173]:
name[3:7] + name[7:11] == name[3:11]
Out[173]:
In [175]:
print name.upper()
In [177]:
print name
In [178]:
# first occurence of "ui" in "Guido":
print "Guido".find("ui")
In [179]:
name = "uwe"
action = "says hello"
print name + " " + action + "!" # "+" concatenates strings
In [180]:
# strings can be multplied with an integer
print "123_" * 4
In [181]:
# the position of the integer factor does not matter
# addition is something we have seen above
print 2 * "123_" + "abc"
In [185]:
number = raw_input("please input number: ")
print number, "times 3 is", number * 3
In [189]:
# correct
number = raw_input("please input number: ")
print number, "times 3 is", float(number) * 3
In [190]:
print int("123") * float("3.141")
In [191]:
print int("a3")
In [192]:
print type(3)
In [193]:
print type(3.0)
In [194]:
print type("")
In [195]:
print type(True)
In [197]:
a = "hi"
a = a + " there"
print a
In [198]:
a = 123
print type(a), a
a = "i am a"
print type(a), a
In [199]:
for i in range(3): # aka for (int i=0; i<3; i++) in C/C++
print i
In [200]:
for i in range(3):
print "i=",
print i
In [201]:
for i in range(3):
print "i=",
print i
In [202]:
for i in range(1, 5):
print i
In [203]:
for i in range(1, 5, 2):
print i
In [204]:
for i in range(1, 3):
for j in range(2, 4):
print i, "times", j, "is", i*j
In [208]:
number = int(raw_input("input number: "))
if number < 0:
print "number is negative"
elif number == 0:
print "number is zero"
else:
print "number is positive"
In [209]:
x = 3
while x > 0:
print x
x -= 1
In [210]:
for i in range(10):
print i
if i > 1:
print "stop"
break
In [211]:
for i in range(5):
print i,
if i % 2 == 0:
print "is even"
continue
print "is odd"
In [212]:
print type(range(3))
In [213]:
for i in [3, 4, 7, 2]:
print i, "squared is", i*i
In [218]:
for ci in "Python":
print ci, chr(ord(ci)+1) # ord returns ascii code of character, chr is inverse
In [219]:
print [3, "hello", 3.12]
In [220]:
print 3 in [1, 2, 4]
In [223]:
print 3 not in [1, 2, 4]
In [224]:
numbers = [1, 3, 2]
numbers.append(4)
print numbers
In [225]:
print numbers[1:3]
In [226]:
print len(numbers)
In [227]:
print type([]), len([])
In [228]:
print [0, 11] * 3
In [229]:
print [1, 2, 3] + [5, 6]
In [230]:
print numbers
In [231]:
numbers[0] = 2
print numbers
In [232]:
numbers.remove(2)
print numbers
In [233]:
li = [3, 4, 2]
# remove all even numbers:
for i in li:
if i % 2 == 0:
li.remove(i)
print li
In [234]:
# PROBLEM: list is changed during execution
li = [3, 4, 2]
# remove all even numbers, iterate over a copy of li:
for i in li[:]:
if i % 2 == 0:
li.remove(i)
print li
In [235]:
for i in (1, 2, 3):
print i
In [236]:
tp = (1, 2, 3)
tp.append(4)
In [237]:
tp = (1, 2, 3, 4)
print tp[-3:-1]
In [238]:
tp = (1, 2, 3)
a, b, c = tp
print a * b * c
In [239]:
a, b, c = 1, 2, 3
In [240]:
x = 1,
print type(x), len(x)
In [241]:
print type(()), len(())
In [242]:
a, b = b, a
print a, b
In [243]:
a_values = [1, 3 ,5]
b_values = [2, 4, 6]
print zip(a_values, b_values)
In [244]:
for a, b in zip(a_values, b_values):
print a + b
In [245]:
words = ["you", "me", "and", "i"]
for i, word in enumerate(words):
print "word", i, "is", word
In [246]:
age_of = { "jan": 18, "alan": 27, "universe": 13.8e9 }
This corresponds to the following table:
key | mapped to |
---|---|
jan | 18 |
alan | 27 |
universe | 13.8e9 |
In [247]:
print age_of["universe"]
In [248]:
print age_of["god"]
In [249]:
print age_of.get("god", "unknown")
In [250]:
print "uwe" in age_of
In [251]:
print age_of.keys(), age_of.values()
In [252]:
print age_of.items()
In [254]:
for who, age in age_of.items():
print who, "is", age, "years old"
In [255]:
a = "abcdabcdfdcdcabcabcabcabcabcaaaab"
counter = dict()
for ai in a:
if ai not in counter:
counter[ai] = 0
counter[ai] += 1
print counter["a"]
In [259]:
a = "abcdabcdfdcdcabcabcabcabcabcaaaab"
counter = dict()
for ai in a:
counter[ai] = counter.get(ai, 0) + 1
print counter["a"]
In [260]:
from collections import Counter
a = "abcdabcdfdcdcabcabcabcabcabcaaaab"
counter = Counter(a)
print counter["a"]
In [261]:
a = set((1, 2, 3))
b = set([2, 3, 4])
print a, b
In [262]:
print a | b
In [264]:
print a.union(b)
In [263]:
print a & b
In [265]:
print a.intersection(b)
In [266]:
print a - b
In [267]:
print a.difference(b)
In [268]:
print type(set()), len(set())
In [269]:
a = [1, [2,3], (3, 4, 5), "abc", { 3: 4 }]
for ai in a:
print ai
In [270]:
a[1].append(4)
print a
In [271]:
numbers = { "even": [2, 4, 6], "odd": [1, 3, 5] }
In [272]:
print numbers["even"][0]
In [273]:
a = { [1,2] : 2 }
In [274]:
a = set()
a.add([1, 2])
In [275]:
values = [3 * a for a in range(10)]
print values
In [276]:
print [3*i for i in values if i % 7 == 6]
In [277]:
def add(a, b, c):
return a + b + c
In [278]:
print add(1, 2, 3)
In [279]:
print add("a", "bc", "def")
In [280]:
print add(1, "a", 3)
In [281]:
def mul(a, b):
return a * b
In [282]:
print mul(3, 4)
In [283]:
print mul(3, "abc")
In [284]:
add(c=1, b=2, a=3)
Out[284]:
In [285]:
add(1, c=2, b=3)
Out[285]:
In [286]:
add(a=2, b=3, 3)
In [287]:
def greet(name, salute_with="hello"):
print salute_with, name, "!"
greet("jan")
In [288]:
greet("urs", "gruezi")
In [289]:
# arbitrary many arguments:
def multiply(v0, *values):
print "got input arguments", v0, "and", values
product = v0
for v in values:
product *= v
return product
print multiply(2, 1, 13, 1)
In [290]:
def func(a, b, c):
result1 = a + b * c
result2 = a - b / c
return result1, result2
In [291]:
r1, r2 = func(1, 2, 3)
print r1, r2
The first string below a function declaration is called a doc string. Calling help() on this function will return this string.
In [292]:
def magic(a, b, c):
""" this function is magic !
it take a, b, c and returns the sum
"""
return a + b + c
In [293]:
help(magic)
You can pass a function to a variable:
In [294]:
new_name = magic
print new_name(1, 2, 3)
And you can pass a function as an argument to a function:
In [295]:
def eval_function(fun, *a):
return fun(*a)
print eval_function(set, (1, 2, 3, 4, 5))
In [296]:
def add(a, li= []):
li.append(a)
return li
li = add(3)
li2 = add(4)
print li
In [297]:
print li is li2
In [298]:
def add(a, li=None):
if li is None:
li = []
li.append(a)
return li
li = add(3)
li2 = add(4)
print li
In [299]:
print li is li2
In [307]:
# first version
class SimpleAddress(object):
"""This class represents a person living in a
city.
"""
def say_hello(self, formula):
""" greets the person """
print formula, self.name, "from", self.city
# maual setting of attributes:
a = SimpleAddress()
a.name = "tina turner"
a.city = "zürich"
# when calling say_hello 'self' is replaced by 'a':
a.say_hello("gruezi")
# TODO: insert print statements
In [308]:
class SimpleAddress(object):
def __init__(self, name, city):
self.name = name
self.city = city
def say_hello(self, formula):
print formula, self.name, "from", self.city
# this 'constructs' an instance aa and calls __init__ with self
# replaced by a and following arguments "tina turner", "zürich"
a = SimpleAddress("tina turner", "zürich")
# when calling say_hello 'self' is replaced by 'a':
a.say_hello("gruezi")
In [309]:
# 1st: methods are attached to the class:
print SimpleAddress.say_hello
In [311]:
print SimpleAddress.__init__
In [312]:
# 2nd: address.say_hello("gruezi") is handled internally as follows:
SimpleAddress.say_hello(a, "gruezi")
In [314]:
# address = Address("tina turner", "zürich") is handled as follows:
address = SimpleAddress.__new__(Address)
SimpleAddress.__init__(a, "tina turner", "zürich")
print a.name
In [315]:
class Vector3D(object):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __add__(self, other):
return Vector3D(self.x + other.x,
self.y + other.y,
self.z + other.z)
def __str__(self):
return "Vector(%f, %f, %f)" % (self.x, self.y, self.z)
v1 = Vector3D(1.0, 2.0, 3.0)
In [316]:
print str(v1)
In [317]:
print v1
In [318]:
v2 = Vector3D(2.0, 0.0, -1.0)
v3 = v1 + v2
print v3
In [319]:
class Dog(object):
def __init__(self, name):
# print "\n.. this is Dog.__init__, self is", self
self.name = name
def greet(self):
# print "\n.. this is Dog.greet, self is", self
print "hi", self.name
def say(self):
# print "\n.. this is Dog.say, self is", self
print "barf"
d = Dog("hasso")
d.greet()
d.say()
In [320]:
class SuperDog(Dog):
def __init__(self):
#print "\n.. this is SuperDog.__init__, self is", self
super(SuperDog, self).__init__("fifi")
def say(self):
#print "\n.. this is SuperDog.say, self is", self
print "BARF !!!"
sd = SuperDog()
sd.greet()
sd.say()
In [321]:
fp = open("text.txt", "w")
print type(fp)
In [322]:
fp.write("line 1\n")
print >> fp, "line 2"
fp.close()
In [324]:
print open("text.txt", "r").read()
In [325]:
print open("text.txt", "r").readlines()
In [326]:
for line in open("text.txt", "r"):
print repr(line)
In [327]:
# use enumeration
for (i, line) in enumerate(open("text.txt", "r")): # tuple unpacking
print "line", i, "is", repr(line)
In [328]:
print 1/0
In [329]:
raise ZeroDivisionError("this is some extra information which is printed below")
In [330]:
int("abc")
In [331]:
try:
int("abc")
except ValueError:
print '"abc" is not a valid number'
In [332]:
def divide(a, b):
return a / b
def secure_divide(a, b):
try:
result = divide(a, b)
except:
result = None
return result
print secure_divide(12, 4), secure_divide(3, 0)
In [333]:
# save the example above in a file "secure_math.py"
import secure_math
print secure_math.secure_divide(12, 4)
In [334]:
!pip install requests
In [337]:
import requests
print requests.get("http://telize.com/jsonip").json()
In [345]:
import numpy as np
x = np.array((1.0, 2, 3))
In [346]:
print x
In [347]:
print x.dtype
In [348]:
# indexing and slicing
print x[0], x[::2]
In [349]:
# assignment:
x[::2] += 1
print x
In [350]:
print 2 * x + x
In [351]:
print x * x
In [352]:
print np.dot(x, x)
In [353]:
print np.sin(x)
In [354]:
print x.shape
In [355]:
# range with known stepsize 0.3
np.arange(0, 2, 0.3)
Out[355]:
In [356]:
# range with known number of points
np.linspace(0, np.pi, 10)
Out[356]:
In [369]:
mat = np.array(((1, 2, 3), (2, 3, 4)), dtype=np.float)
In [370]:
print mat
In [371]:
print mat.shape
In [372]:
mat * mat
Out[372]:
In [373]:
np.dot(mat, x)
Out[373]:
In [374]:
print mat.T
In [375]:
print np.dot(mat, mat.T)
In [376]:
print np.eye(3)
In [377]:
print np.zeros((2, 3))
In [378]:
np.diag(np.arange(1, 4))
Out[378]:
In [379]:
# complex matrices
In [380]:
mat = np.array(((1.0, 1+1j), (1-1j, 2.0)), dtype=np.complex)
print mat
In [381]:
print np.dot(mat, mat.T.conj())
In [382]:
vec = np.arange(3)
print vec
In [384]:
# create matrix with artificial column dimensions
vec_as_matrix = vec[:, np.newaxis]
print vec_as_matrix
In [385]:
# and back:
vec_back = vec_as_matrix.squeeze()
print vec_back
In [401]:
vec = np.arange(24, dtype=np.int)
print vec
In [402]:
mat = vec.reshape(3, -1)
print mat
In [403]:
print mat.reshape(-1, 3)
In [404]:
print mat.reshape(3, 4, -1)
In [405]:
print mat
In [406]:
mat % 3 == 0
Out[406]:
In [407]:
mat[mat % 3 == 0] = 0
print mat
In [408]:
print mat.dtype
mat = mat.astype(np.float)
print mat.dtype
print mat
In [409]:
mat.tofile("matrix.bin")
print mat.dtype
In [410]:
print np.fromfile("matrix.bin", dtype=np.float64)
In [411]:
print np.fromfile("matrix.bin", dtype=np.float64).reshape(3, -1)
In [412]:
np.fromfile("matrix.bin", dtype=complex)
Out[412]:
In [414]:
np.fromfile("matrix.bin", dtype=np.int)
Out[414]:
In [415]:
np.savetxt("matrix.txt", mat)
In [416]:
np.loadtxt("matrix.txt")
Out[416]:
In [417]:
print open("matrix.txt").read()
In [422]:
# this is just for this presentation !
%matplotlib inline
In [423]:
import pylab
x = np.linspace(0, 2 * np.pi, 150)
y = np.sin(x) * np.cos(x*x+1)
pylab.plot(x, y, label="y")
y2 = y * np.sin(y)
pylab.plot(x, y2, label="y2")
pylab.legend()
pylab.show()
In [426]:
# 2 x 1000 matrix with normal distributed entries:
points = np.random.randn(2, 1000)
In [427]:
import pylab
pylab.plot(points[0,:], points[1,:], ".")
pylab.show()
In [428]:
deformation_matrix = np.array(((1.5, 1.0), (0.9, 1.0)))
In [429]:
x = np.dot(deformation_matrix, points)
In [430]:
import pylab
pylab.plot(x[0,:], x[1,:], ".")
pylab.show()
In [431]:
# np.linalg.eigh is eigenvalue decomposition of hermetian matrix
# np.linalg has others like
# np.linalg.solve for solving linear equation systems
# np.linalg.svd for singular value decomposition and others
# this is pca for centered matrix
eigvals, eigvecs = np.linalg.eigh(np.dot(x, x.T))
In [432]:
# column vectors describe main directions in data:
print eigvecs
In [433]:
# plot data again
pylab.plot(x[0,:], x[1,:], ".")
# plot lines describing directions of main variance:
pylab.plot([-3*eigvecs[0,0], 3*eigvecs[0,0]], [-3 * eigvecs[0,1], 3 * eigvecs[0,1]], 'g', linewidth=2)
pylab.plot([-3*eigvecs[1,0], 3*eigvecs[1,0]], [-3 * eigvecs[1,1], 3 * eigvecs[1,1]], 'g', linewidth=2)
pylab.show()
In [ ]:
In [ ]: