a GGNB short method course offered by Debsankha Manik and Jana Lassar at the MPI for Dynamics and Self-Organization in September 2014
Markdown is a lightweight markup language.
This is a list:
A numbered list:
LaTeX equations
\begin{align} f(x \; | \; \mu, \sigma) = \frac{1}{\sigma\sqrt{2\pi} } \; e^{ -\frac{(x-\mu)^2}{2\sigma^2} } \end{align}And this is a link where you find more about markdown syntax.
In [4]:
# print( # Tab now should display the docstring
# Also woks:
print??
In [5]:
def isprime(n):
"""Determine if a given number is a prime number"""
for x in range(2, n-1):
if n % x == 0: #if n modulo x equals 0
return False #then n is not a prime number
return True
In [6]:
isprime??
In [7]:
%matplotlib inline
import pylab as pl
import numpy as np
from IPython.html.widgets import interact
def plot(frequency):
x = np.arange(1000)
pl.plot(x, np.sin(2*np.pi*frequency*x/1000))
interact(plot, frequency=(0,20,1))
In [8]:
#name = object
a = 17
b = 3.14
c = "bla"
In [9]:
print(a)
print(b)
print(c)
In [10]:
print(type(a))
print(type(b))
print(type(c))
In [11]:
a = 17
a = "Used names can always be reassigned to other objects regardles of their data type!"
print(a)
In [12]:
print(int(5.5))
print(float('5.23'))
print(str(12))
print(bool('True'))
In [217]:
print(x+y)
print("bla" + "bla")
print(x/y)
print(x*2)
print('bla'*3)
print(x/2)
print(x**3) #the exponentiation operator
print(x%2) #the remainder operator
Out[217]:
Operator | True, if |
---|---|
a == b | a equals b |
a > b | a is larger than b |
a < b | a is smaller than b |
a >= b | a is larger than b or equals b |
a <= b | a is smaller than b or equals b |
a != b | a and b are unequal |
a is b | a is the same object as b |
a is not b | a is not the same object as b |
In [61]:
print(x==y)
print(x==5)
In [15]:
x = 3
y = 3
x is y
Out[15]:
'==' compares values while 'is' compares identities
In [16]:
x = [1]
y = [1]
x is y
Out[16]:
But:
In [64]:
x==y
Out[64]:
Warning: do not check equality of two floats (finite precision!!)
In [70]:
from math import sin, pi
sin(2*pi)==0
Out[70]:
In [53]:
number_of_people = 6
if number_of_people < 5:
print('Not enough people to play this game.')
elif number_of_people < 10:
print('More would be better, but its sufficient.')
elif number_of_people < 20:
print('Perfect! Enjoy!')
elif number_of_people < 30:
print('Less would be better, but it will work somehow.')
else:
print('Sorry, but more than 30 is too much.')
Conditional expressions:
In [55]:
x = 12
#the long version:
if x%2==0:
message = "Even."
else:
message = "Odd."
print(message)
#the short version:
print( "Even." if x%2==0 else "Odd." )
In [71]:
value = 17
while value < 21:
print(value)
value = value + 1
In [72]:
value = 17
max_value = 30
while True:
value = value + 1
if value > max_value:
break #stop here and escape the while loop
elif value%2==0:
continue #stop here and continue the while loop
print(value)
Sequence | mutable? | data type |
---|---|---|
list | yes | arbitrary |
tuple | no | arbitrary |
string | no | Unicode symbols |
In [74]:
a = [1,2,3,4,5] #a list
b = (1,2,3,4,5) #a tuple
c = '12345' #a string
Since lists and tuples can contain arbitrary data types, they can be 'nested':
In [75]:
nested_list = [[1,2,3],[4,5,6],[7,8,9]]
All three sequence types (tuples, strings and lists) share much of their syntax and functionality.
In [77]:
print(len(a),len(b),len(c))
In [78]:
print( a + a )
print( b + b )
print( c + c )
single items are accessible by their index (starting from 0):
In [80]:
print( a[0], b[1], c[2] )
Negative indices are counted from the end (starting with -1)
In [ ]:
print ( a[-1], b[-3] )
A subset of items can be accessed by "slices".
Syntax: [I:J:K] means start from index I, stop at index J and take every K'th item. If I is omitted, start from the first item, if J is omitted, stop at the last item, and if K is omitted, take every item.
In [82]:
print( a[1:4] ) #get items from 1 to 4
print( a[3:5] ) #get items from 3 to 5
print( a[:4] ) #get items from 0 to 4
print( a[3:] ) #get items from 3 to the end
print( a[::2] ) #get every second item
The in-operator checks whether an item is in the sequence:
In [83]:
print((2,3) in (1,2,3,4,5))
print('cde' in 'abcdefgh')
In [86]:
a = [1,2,3,4] #create list
a[2] = 12 #replace item 2 by value 12
a.append(34) #add value 34 to the end
a.extend([0,0,0]) #add several values to the end
a.pop() #remove last item
a.insert(3, 'blub')#insert object before index 3
a.reverse() #reverse list
print(a)
In [93]:
s = [1,2]
t = s
t.append(99)
print(s, t)
In [87]:
# Strings can be enlosed by both single quote and double quote.
s='My home'
t="My home"
s==t
Out[87]:
strings can contain quotation marks themselves. single/double quotes become important then:
In [94]:
newstring="This is Mary's home"
anotherstring='And he said: "Let there be light"'
# And if you **really** need it, both single and double quotes:
huge_string="""This 'string' contains "both" types of quote"""
In [88]:
print(huge_string.upper())
print(huge_string.startswith('a'))
print(huge_string.find('contain'))
print(huge_string.split(' '))
print(huge_string.count('s'))
Remember how while
loops were prone to infinite loop bugs?
Python gives you a chance to avoid them in most cases:
In [96]:
i = 1
while i < 50:
if i%7 == 0:
print(i)
i += 1
In [97]:
for i in range(1, 50, 1):
if i%7 == 0:
print(i)
In [103]:
count = 0
st = "home, sweet home"
for char in st:
if char == 'h':
count += 1
print("%c appears %d times in \"%s\""%('h', count, st))
In [108]:
print("%s is %d years old"%('John', 34))
print("{name} is {age} years old, {name} has 3 children".format(name='John', age=34))
For-loops can not only iterate through sequences, but also through 'iterable' objects, like range().
In [109]:
#Example: We want to sum up all numbers betwen 0 and 100.
#Instead of manually typing a list of all numbers, we can use range:
s = 0
for i in range(101):
s = s + i
print(s)
In [110]:
#long version: "for-loop"
li = []
for i in range(100):
li.append(i*2)
#short version:
li = [2*i for i in range(101)]
print(li)
List comprehensions can be used as a filter:
In [119]:
li = [1/i for i in range(101) if i != 0]
print(li)
Also to place a default value
In [123]:
li = [1/i if i!=0 else None for i in range(101) ]
print(li)
And to write insanely obtuse code and mess with your collaborators :D
In [136]:
nested_list = [[1,2], [3], [4,5,6]]
flattened_list = [item for sublist in nested_list for item in sublist]
print(flattened_list)
They are almost like lists, but immutable:
In [138]:
l = [1,2,3,4,5]
t = [1,2,3,4,5]
#or, simply:
t = tuple(l)
In [141]:
print(l[2:5])
print(t[2:5])
print(2 in l)
print(2 in t)
In [143]:
l[2] = 99
print(l)
t[2] = 99
print(t)
What's the use of immutability? glad you asked
stores key->value pairs:
In [144]:
d={'germany':'berlin', 'france':'paris', 'poland':'warsaw', 'denmark':'copenhagen'}
In [145]:
d['germany']
Out[145]:
You can add keys anytime:
In [146]:
d['belgium']='brussels'
useful things you can do with dictionaries:
In [147]:
d.keys()
Out[147]:
In [148]:
d.values()
Out[148]:
Any datatype can be used as a key in dictionary, so long as it is hashable
Thumbrule: integer, float, tuple, string are OK; list, other dictionaries are NOT OK
In [150]:
mycrazydict = {(1,3,7):'odd!', [2,4,6]: 'even!'}
In [151]:
def triple(x):
return x*3
In [152]:
triple(4)
Out[152]:
Very important: writing documentation for your code
In [153]:
def triple(x):
"""
This function accepts a number, returns 3 times that number.
"""
return x*3
In [154]:
triple #Shift+tab shows documentation in ipython
Out[154]:
In [155]:
help(triple) #this also works
when you pass any object to a function, any change done to the object will affect it globally:
In [156]:
def modify(l):
l.append(23)
return 0
In [158]:
l=[1,2,3]
modify(l)
print(l)
but reassignments inside the function is not reflected globally
In [ ]:
def change(l):
l=[1,2,34]
return 0
mylist=[3,6]
change(mylist)
print mylist
One of the most useful things about python is that there are tons of modules available, that do many of the tasks you might need to do:
In [ ]:
import math
math.sin(0.1)
In [ ]:
help(math)