Workshop for the "Training in Network Management Systems and Analytical Tools for Seismic"¶

This notebook is a very quick introduction to Python and in particular its scientific ecosystem in case you have never seen it before. It furthermore grants a possibility to get to know the IPython/Jupyter notebook. See here for the official documentation of the Jupyter notebook - a ton more information can be found online.

A lot of motivational writing on Why Python? is out there so we will not repeat it here and just condense it to a single sentence: Python is a good and easy to learn, open-source, general purpose programming language that happens to be very good for many scientific tasks (due to its vast scientific ecosystem).

You might eventually have a need to create some custom plots. The quickest way to success is usually to start from some example that is somewhat similar to what you want to achieve and just modify it. These websites are good starting points:

This course is fairly non-interactive and serves to get you up to speed with Python assuming you have practical programming experience with at least one other language. Nonetheless please change things and play around an your own - it is the only way to really learn it!

The first part will introduce you to the core Python language. This tutorial uses Python 3 but almost all things can be transferred to Python 2. If possible choose Python 3 for your own work!

Python is dynamically typed and assigning something to a variable will give it that type.

In [ ]:

# Three basic types of numbersa=1# Integersb=2.0# Floating Point Numbersc=3.0+4j# Complex Numbers, note the use of j for the complex part# Arithmetics work as expected.# Upcasting from int -> float -> complexd=a+b# (int + float = float)print(d)e=c**2# c to the second power, performs a complex multiplicationprint(e)

Just enclose something in single or double quotes and it will become a string. On Python 3 it defaults to unicode strings, e.g. non Latin alphabets and other symbols.

In [ ]:

# You can use single or double quotes to create strings.location="New York"# Concatenate strings with plus.where_am_i='I am in '+location# Print things with the print() function.print(location,1,2)print(where_am_i)# Strings have a lot of attached methods for common manipulations.print(location.lower())# Access single items with square bracket. Negative indices are from the back.print(location[0],location[-1])# Strings can also be sliced.print(location[4:])

Save your name in all lower-case letters to a variable, and print a capitalized version of it. Protip: Google for "How to capitalize a string in python". This works for almost any programming problem - someone will have had the same issue before!

Python has two main collection types: List and dictionaries. The former is just an ordered collection of objects and is introduced here.

In [ ]:

# List use square brackets and are simple ordered collections of things.everything=[a,b,c,1,2,3,"hello"]# Access elements with the same slicing/indexing notation as strings.# Note that Python indices are zero based!print(everything[0])print(everything[:3])print(everything[2:-2])# Negative indices are counted from the back of the list.print(everything[-3:])# Append things with the append method.everything.append("you")print(everything)

The other main collection type in Python are dictionaries. They are similiar to associative arrays or (hash) maps in other languages. Each entry is a key-value pair.

In [ ]:

# Dictionaries have named fields and no inherent order. As is# the case with lists, they can contain anything.information={"name":"Hans","surname":"Mustermann","age":78,"kids":[1,2,3]}# Acccess items by using the key in square brackets.print(information["kids"])# Add new things by just assigning to a key.print(information)information["music"]="jazz"print(information)# Delete things by using the del operatordelinformation["age"]print(information)

The key to conquer a big problem is to divide it into many smaller ones and tackle them one by one. This is usually achieved by using functions.

In [ ]:

# Functions are defined using the def keyword.defdo_stuff(a,b):returna*b# And called with the arguments in round brackets.print(do_stuff(2,3))# Python function also can have optional arguments.defdo_more_stuff(a,b,power=1):return(a*b)**powerprint(do_more_stuff(2,3))print(do_more_stuff(2,3,power=3))# For more complex function it is oftentimes a good idea to #explicitly name the arguments. This is easier to read and less error-prone.print(do_more_stuff(a=2,b=3,power=3))

To use functions and objects not part of the default namespace, you have import them. You will have to do this a lot so it is necessary to learn how to do it.

In [ ]:

# Import anything, and use it with the dot accessor.importmatha=math.cos(4*math.pi)# You can also selectively import things.frommathimportpib=3*pi# And even rename them if you don't like their name.frommathimportcosascosinec=cosine(b)

Loops and conditionals are needed for any non-trivial task. Please note that whitespace matters in Python. Everything that is indented at the same level is part of the same block. By far the most common loops in Python are for-each loops as shown in the following. While loops also exist but are rarely used.

In [ ]:

temp=["a","b","c"]# The typical Python loop is a for-each loop, e.g.foritemintemp:# Everything with the same indentation is part of the loop.new_item=item+" "+itemprint(new_item)print("No more part of the loop.")

In [ ]:

# Useful to know is the range() function.foriinrange(5):print(i)

The second crucial control flow structure are if/else conditional and they work the same as in any other language.

In [ ]:

# If/else works as expected.age=77ifage>=0andage<10:print("Younger ten.")elifage>=10:print("Older than ten.")else:print("wait what?")

In [ ]:

# List comprehensions are a nice way to write compact loops.# Make sure you understand this as it is very common in Python.a=list(range(10))print(a)b=[iforiinaifnoti%2]print(b)# Equivalant loop for b.b=[]foriina:ifnoti%2:b.append(i)print(b)

You will eventually run into some error messages. Learn to read them! The last line is often the one that matters - reading upwards traces the error back in time and shows what calls led to it. If stuck: just google the error message!

The SciPy Stack forms the basis for essentially all applications of scientific Python. Here we will quickly introduce the three core libraries:

NumPy

SciPy

Matplotlib

The SciPy stack furthermore contains pandas (library for data analysis on tabular and time series data) and sympy (package for symbolic math), both very powerful packages, but we will omit them in this tutorial.

importnumpyasnp# Create a large array with with 1 million samples.x=np.linspace(start=0,stop=100,num=1E6,dtype=np.float64)# Most operations work per-element.y=x**2# Uses C and Fortran under the hood for speed.print(y.sum())# FFT and inversex=np.random.random(100)large_X=np.fft.fft(x)x=np.fft.ifft(large_X)

"99 Bottles of Beer" is a traditional song in the United States and Canada. It is popular to sing on long trips, as it has a very repetitive format which is easy to memorize, and can take a long time to sing. The song's simple lyrics are as follows:

99 bottles of beer on the wall, 99 bottles of beer.
Take one down, pass it around, 98 bottles of beer on the wall.

The same verse is repeated, each time with one fewer bottle. The song is completed when the singer or singers reach zero.

Your task here is write a Python program capable of generating all the verses of the song.

In cryptography, a Caesar cipher is a very simple encryption techniques in which each letter in the plain text is replaced by a letter some fixed number of positions down the alphabet. For example, with a shift of 3, A would be replaced by D, B would become E, and so on. The method is named after Julius Caesar, who used it to communicate with his generals. ROT-13 ("rotate by 13 places") is a widely used example of a Caesar cipher where the shift is 13. In Python, the key for ROT-13 may be represented by means of the following dictionary: