2Rufe eine selbst geschriebene Mischungs-Funktion auf [39:17]
Zum Programmieren verwenden wir Befehle, das sollte recht einleuchtend sein. Nun hat Python natürlich keine Befehle für die Geochemie, um mit so einem beispielsweise direkt auszurechnen wie die neue Zusammensetzung einer Schmelze ist, nachdem sie sich mit einer anderen gemischt hat. Praktisch wäre es aber schon. Nicht nur in der Geochemie, sondern für sehr vieles. Daher ist es möglich eigenen Befehle zu definieren – etwas zur Mischung von Magmen – um diese anschließend immer wieder zu verwenden. Es ist sogar möglich mehrere Befehle in einer Datei zu speichern, und aus dieser ›Bibliothek‹ immer wieder aufzurufen. Wie das geht lernen wir in dieser Einheit.
operators, variables, print(), extract with [ ] Available Notebooks: Lecture, Exercise, Solution
Wir starten mit ein paar grundsätzlichen Dingen, welche noch nicht wirklich etwas mit dem Ziel dieser Einheit zu tun haben, aber gut zu wissen sind, bevor es richtig los geht.
Video nb
Variables
a =2print(a)res =5res_3 =7
2
Operators
print(5+3)7*8
8
56
Indents
if a <=3: #indents are part of the code a =5print(a)
For a better and quicker comprehension of the code.
Underscores are allowed in variables
✓True
✗False
Indents are critical parts when coding functions
✓True
✗False
Which symbol is used for inline comments?
✗@
✗$
✓#
✗&
Practise
First, make a list containing 4 Si concentrations, assing this list to the variable ‘si’, and display the content of this variable.
Then, for a real challenge:
Adjust the code so that you can choose which databases are shown – but so that they ar shown together, not individually.
Extract the third element from this list.
Subtract the fourth from the first list element.
Produce a nested list. To do this, first produce a second ist of 4 Si concentrations.
Use the variables to produce a nested list, and assign this nested list to the variable ‘siAll’, and display its content.
Finally, extract the vlaue ‘5.23’, i.e., the third element from the e second element of the siAll list.
Functional Programming and Object Oriented Programming
Assumme the command: si.append(14.83) – what is the part .append(14.83) called?
✗variable
✗function
✓method
✗attribute
Assumme the command: len([12.31, 24.21, 17.55]) – what is this command called?
✗variable
✓function
✗method
✗attribute
Practise
We have the following list of Cr concentrations:
First, we have new measurements and want to append these as a third element to alData, and then display the content of alData.
We then want to know the length of alData, and a single element within alData.
We then want to know the length of alData, and a single element within alData. Display the result with 2 decimal digits.
Produce a list with 5 values and store it in the variable ‘test’.
Choose (or change) the values so that the command ‘test.count(5)’ displays the result 3.
Then, clear the list, and display the empty list.
Finally, sort the elements (=values) in the last element of crData – and display the enire crData list, in which the last element is then sorted.
Try to do this using (i) a function and using (ii) a method. Which one do you prefer, and why?
# number of elements in alDataprint(len(crData))# number of elements in a single element of alDataprint(len(crData[0]))
3
4
res =sum(crData[1])print(round(res, 2))# OR, in one lineround(sum(crData[1]), 2)
5.27
5.27
test = [5, 4, 5, 8, 5]print(test.count(5))test.clear()print(test)
3
[]
# using a function it is possible to sort the last element,# but it would then require a number of additional steps# to replace the current last element with the newly sorted# last element. I will not follow this up, as this is simpler# done using a method.print(sorted(crData[2]))# using a methodcrData[2].sort()crData
Wirklich sehr häufig muss ein und dieselbe Rechnung zig-Mal durchgeführt werden. Zum Beispiel wenn für 500 Proben die Oxide- in Element-Gew% umgerechnet werden müssen. Man bewegt sich also in einer wahren Schleife mit der immer gleich Rechnung. Schmerzfreie Computer führen solchen Schleifen in atemberaubender Geschwindigkeit, und mit nur wenig Befehlszeilen durch. Daher sind Schleifen sehr wichtig und eine Kernfunktion der Programmierung. Deshalb schauen wir uns nun an, wie diese funktionieren und wir diese anwenden.
Video nb
mgo = [23, 43, 4] # wt%mg = []for i in mgo: res =round(i *0.603, 2) mg.append(res)print(mg)
[13.87, 25.93, 2.41]
for i inrange(5): res = i **2print(res)
0
1
4
9
16
Briefly describe what a for loop is and how it works.
A for loop applies an algorithm (=program) to each element of a list.
All code lines that are part of the for loop need to be indented
✓True
✗False
The line with for … needs to be closed with a ___
✗comma
✗semicolon
✓colon
✗full stop
Practise I
You measured some isotope data, but when calculating the \(\delta\)-value, you forgot to subtract the 1.
Code a for loop that subtracts 1 from each value and displays the results.
Then store the recalculated data in a new list called ‘recalculatedFeIsoData’.
Further, all values shall have only 2 decimals.
Display the content of recalculatedFeIsoData.
Solution
feIsotopeData = [-1.18, 1.09, -0.07, -0.74, 1.23]for i in feIsotopeData: res = i -1print(res)
feIsotopeData = [-1.18, 1.09, -0.07, -0.74, 1.23]recalculatedFeIsoData = []for i in feIsotopeData: res =round(i -1, 2) recalculatedFeIsoData.append(res)recalculatedFeIsoData
[-2.18, 0.09, -1.07, -1.74, 0.23]
Practise II
Assume a simple list with the following elements:
l = [2, 4, 7, 2, 4, 6]
We can get the third element using:
l[2]
7
If we want to have the second to fourth element, this is possible using: Note: As list counting starts with 0, the fourth element is indexed with 3. However, we need to use 4 in this command, as the command means: up to, but not including the fourth elemnt. This is something called exclusive. There are other commands, in which the numbering is inclusive. This is not critical at the moment, but a good occasion for a heads up of this slightly kind of awkwardness.
l[1:4]
[4, 7, 2]
In a for loop, we can also use range in the following way to get the numbers 0, 1, 2 (btw: this gives some insights into why there is this thing of ‘exclusive’ – can you guess why?):
for i inrange(1, 3):print(i)
1
2
Now a challenge: We have two lists of Cr concentrations, each with a different lengths of their elements:
In the following, we are now only interested in the first element of each of the lists (whic itself is also a list).
Then, we want the sum of:
the sum of the first element of each of the lists (which of course is identical to the value of the first element)
the sum of the first two elements of each of the lists
the sum of the first three elements of each of the lists
the sum of the first four (=all) elements of each of the lists – this, of course, only applies to crData1
Now, code a program that outputs these sums.
Got it? And up for one more step?
Now:
In the previous program, we hard coded the number of elements in the range command. This time, code it so that the number of elements is automatically determined in the range command.
In the previous programm, the name of the dataset is part of the for loop. We do not want that any more, in particular if this name might occur multiple times. Therefore, assign the dataset name to the variable ‘data’, and use this variable in the for loop.
Let the values only have 2 decimals.
Store the final results as a list in the variable moving_average, and disply this list.
Solution
for i inrange(1, 5): res =sum(crData1[0][0:i])print(res)
data = crData1moving_average = []for i inrange(1, len(data[0]) +1): res =sum(data[0][0:i]) res =round(res, 2) # it is possible to assign a new value to an already used variable, this line could be included in the previous or next line moving_average.append(res)moving_average
[0.87, 2.27, 3.26, 5.27]
What’s wrong with this code? (NONE YET)
coming
Solution
coming
2.4 Command- def, return, import & making own commands and importing these [09:27]
Available Notebooks: Lecture, Exercise, Solution
Und schon jetzt wird es wirklich cool: wir basteln uns einen eigenen Befehl, und legen den in einer Datei ab. Diese Datei können wir fortan importieren wenn wir den Befehl brauchen, und diesen dann einfach anwenden. – Die Datei lässt sich ab sofort um immer mehr Befehle erweitern, welche in der Mineralogie nützlich sind: Aufschmelzung, Mischung, Umrechnungen, Formelberechnung, Isotopen-Fraktionierungen, Gesteinsalter, Thermobarometrie, jegliche Modelle – und vieles mehr.
Unit 2.4 will soon be replaced with other options for import.
2.5 Task - Building a ratio mixing command [03:35]
Available Notebooks: Solution
Zum Abschluss sollst Du Deinen ersten, eigenen Befehl schreiben. Natürlich gleich einen nützlichen.
For the import to work, it is important the modules folder is in the folder where this notebook is stored. (I.e., not in the modules folder, but the parent folder to this above.)
import modules.mineralogyModule as mi
r1El1 =22.34# MgO in Rock 1 in wt%r1El2 =2.58# FeO in Rock 1 in wt%r2El1 =25.84# MgO in Rock 2 in wt%r2El2 =7.66# FeO in Rock 2 in wt%mi.mixRatios(r1El1, r1El2, r2El1, r2El2, .8) # X is the fraction of rock 1