SharedPythonLoopsToFunctions.ipynbOpen in CoCalc
Views : 3
Description: Python - Software Carpentry at Koper 2018
In [1]:
import numpy

In [11]:
import matplotlib.pyplot

In [12]:
matplotlib.pyplot.plot(data_ave)
matplotlib.pyplot.show()

In [22]:
data = numpy.loadtxt(fname='./data/inflammation-03.csv',
delimiter=',')
data_ave = numpy.mean(data, axis=0)
data_max = numpy.max(data, axis=0)
data_min = numpy.min(data, axis=0)
matplotlib.pyplot.plot(data_ave, label='average')
matplotlib.pyplot.plot(data_max, label='max')
matplotlib.pyplot.plot(data_min, label='min')
matplotlib.pyplot.ylabel('inflammation')
matplotlib.pyplot.xlabel('day')
matplotlib.pyplot.title('inflammation-03.csv')
matplotlib.pyplot.legend()
matplotlib.pyplot.show()

In [29]:
word = 'oxygen'
for char in word:
print(char)

o x y g e n
In [32]:
vowels = 0
for vowel in 'aiueo':
vowels = vowels + 1
print("Now at",vowel)
print("Vowels: ",vowels)

Now at o Vowels: 5
In [33]:
print("Vowels: ", len('aiueo'))

Vowels: 5
In [35]:
for n in range(1,4):
print(n)

1 2 3
In [39]:
result = 1
for p in range(3):
result = result * 5

print(result)
print(5 ** 3)

125 125
In [40]:
xs = [1,2,3]
for i, x in enumerate(xs):
print("i=", i, ", x=", x)

i= 0 , x= 1 i= 1 , x= 2 i= 2 , x= 3
In [42]:
cc = [2, 4, 3]
x = 5
result = 0
for i, c in enumerate(cc):
result = result + c * x**i
print(result)

97
In [43]:
odds = [1, 3, 5, 7]
print("odds are", odds)

odds are [1, 3, 5, 7]
In [44]:
print("first odd", odds[0])

first odd 1
In [46]:
print("second to last odd", odds[-2])

second to last odd 5
In [47]:
for number in odds:
print(number)

1 3 5 7
In [48]:
names = ["Curie", "Darwing", "Turing"]
print("names are", names)

names are ['Curie', 'Darwing', 'Turing']
In [49]:
names[1] = "Darwin"

In [50]:
print("names are now", names)

names are now ['Curie', 'Darwin', 'Turing']
In [52]:
name = "Darxin"

In [53]:
name[3] = "w"

----------------------------------------- TypeErrorTraceback (most recent call last) <ipython-input-53-a52eec4d30d4> in <module>() ----> 1 name[3] = "w" TypeError: 'str' object does not support item assignment 
In [56]:
salsa = ["peppers", "onions", "cilantro", "tomatoes"]
my_salsa = list(salsa)
my_salsa[0] = "hot peppers"
print("my salsa",my_salsa)

my salsa ['hot peppers', 'onions', 'cilantro', 'tomatoes']
In [57]:
print("original salsa", salsa)

original salsa ['peppers', 'onions', 'cilantro', 'tomatoes']
In [58]:
x = [["pepper", "zucchini", "onion"],
["cabbage", "lettuce", "garlic"],
["apple", "pear", "banana"]]
print(x[0])

['pepper', 'zucchini', 'onion']
In [59]:
print([x[0]])

[['pepper', 'zucchini', 'onion']]
In [60]:
print(x[0][0])

pepper
In [61]:
x = [1, 2.0, 'ABC', [1, "D"]]
print(x)

[1, 2.0, 'ABC', [1, 'D']]
In [63]:
x[0] = 'more pepper'
print(x)

['more pepper', 2.0, 'ABC', [1, 'D']]
In [64]:
x.append("append this")
print(x)

['more pepper', 2.0, 'ABC', [1, 'D'], 'append this']
In [65]:
del x[2]

In [66]:
print(x)

['more pepper', 2.0, [1, 'D'], 'append this']
In [67]:
x.reverse()
print(x)

['append this', [1, 'D'], 2.0, 'more pepper']
In [68]:
x.pop()
print(x)

['append this', [1, 'D'], 2.0]
In [71]:
odds = [1,3,5,7]
primes = list(odds)
primes.append(2)
print("primes are",primes)

primes are [1, 3, 5, 7, 2]
In [72]:
print("odds are",odds)

odds are [1, 3, 5, 7]
In [73]:
print("h" + "e")

he
In [74]:
word = "hello"
result = []
for char in word:
result.append(char)
print(result)

['h', 'e', 'l', 'l', 'o']
In [75]:
result2 = ""
for char in result:
result2 = result2 + char
print(result2)

hello
In [82]:
string_for_slicing = "Observation date: 02-Feb-2013"
list_for_slicing = [["fluorine", "F"],["chlorine", "Cl"],
["bromine", "Br"], ["iodine", "I"],
["astatine", "At"]]
print(string_for_slicing[-4:])
print(list_for_slicing[-4:])

2013 [['chlorine', 'Cl'], ['bromine', 'Br'], ['iodine', 'I'], ['astatine', 'At']]
In [90]:
%cd /home/jule/proj/stim

/home/jule/proj/stim
In [83]:
import glob

In [95]:
files = glob.glob('./data/inflammation-*.csv')
files.sort()
for f in files:
delimiter=',')
data_ave = numpy.mean(data, axis=0)
data_max = numpy.max(data, axis=0)
data_min = numpy.min(data, axis=0)
matplotlib.pyplot.plot(data_ave, label='average')
matplotlib.pyplot.plot(data_max, label='max')
matplotlib.pyplot.plot(data_min, label='min')
matplotlib.pyplot.ylabel('inflammation')
matplotlib.pyplot.xlabel('day')
matplotlib.pyplot.title(f)
matplotlib.pyplot.legend()
matplotlib.pyplot.show()

In [102]:
files = glob.glob('./data/inflammation-*.csv')
files.sort()
data0_ave = numpy.mean(data0, axis=0)
data1_ave = numpy.mean(data1, axis=0)
diff = data0_ave - data1_ave
matplotlib.pyplot.plot(diff)
matplotlib.pyplot.title("Difference of averages")
matplotlib.pyplot.show()

In [105]:
filenames = glob.glob('./data/inflammation*.csv')
composite_data = numpy.zeros((60,40))
for f in filenames:
composite_data += data
composite_data /= len(filenames)

data_ave = numpy.mean(composite_data, axis=0)
data_max = numpy.max(composite_data, axis=0)
data_min = numpy.min(composite_data, axis=0)
matplotlib.pyplot.plot(data_ave, label='average')
matplotlib.pyplot.plot(data_max, label='max')
matplotlib.pyplot.plot(data_min, label='min')
matplotlib.pyplot.ylabel('inflammation')
matplotlib.pyplot.xlabel('day')
matplotlib.pyplot.title('inflammation-averaged.csv')
matplotlib.pyplot.legend()
matplotlib.pyplot.show()

In [106]:
num = 37
if num > 100:
print("greater")
else:
print("not greater")

not greater
In [108]:
num = 53
if num > 100:
print("greater")
elif num == 0:
print("it's zero")
elif num == 42:
else:
print("?")

?
In [111]:
if (1 > 0) or (-1 < 0):
print("one of them is true (or both)")
else:
print("none is true")

one of them is true (or both)
In [119]:
data = numpy.loadtxt(fname="./data/inflammation-01.csv",
delimiter=',')
data_max = numpy.max(data, axis=0)
data_min = numpy.min(data, axis=0)
if data_max[0] == 0 and data_max[20] == 20:
print("This data has suspicious maxima")
elif numpy.sum(data_min) == 0:
else:
print("Seems Ok")

This data has suspicious maxima
In [123]:
if not '':
print('not (empty string) is true')
if 'word':
print('word is true')
if []:
print('empty list is true')
if [1, 2, 3]:
print('non-empty list is true')
if 0:
print('zero is true')
if -1:
print('-one is true')

not (empty string) is true word is true non-empty list is true -one is true
In [126]:
3 > 2 > 1

True
In [127]:
3 > 2 < 4 "==" 3 > 2 and 2 < 4

True
In [136]:
a = data_max[0]
b = data_max[1]
#if .9*b < a < 1.1*b:
if abs(b-a) <= .1*b:
print("True")
else:
print("False")

False
In [137]:
def fahr_to_celsius(temp):
return ((temp - 32) * (5/9))

In [139]:
print("freezing point of water", fahr_to_celsius(32),"C")
print("boiling point of water", fahr_to_celsius(212),"C")

freezing point of water 0.0 C boiling point of water 100.0 C
In [156]:
def celsius_to_kelvin(temp_c):
return temp_c + 273.15

In [149]:
print("freezing point of water", celsius_to_kelvin(0),"K")

freezing point of water 273.15 K
In [157]:
def fahr_to_kelvin(temp_f):
temp_c = fahr_to_celsius(temp_f)
temp_k = celsius_to_kelvin(temp_c)
return temp_k

In [158]:
print("freezing point of water", fahr_to_kelvin(32),"K")

freezing point of water 273.15 K
In [170]:
def plot_inflammation(f):
"""
Plot the averages, maxima, and minima of the columns
in the file called f.
"""
delimiter=',')
data_ave = numpy.mean(data, axis=0)
data_max = numpy.max(data, axis=0)
data_min = numpy.min(data, axis=0)
matplotlib.pyplot.plot(data_ave, label='average')
matplotlib.pyplot.plot(data_max, label='max')
matplotlib.pyplot.plot(data_min, label='min')
matplotlib.pyplot.ylabel('inflammation')
matplotlib.pyplot.xlabel('day')
matplotlib.pyplot.title(f)
matplotlib.pyplot.legend()
matplotlib.pyplot.show()

def check_data(f):
data_max = numpy.max(data, axis=0)
data_min = numpy.min(data, axis=0)
if data_max[0] == 0 and data_max[20] == 20:
print("This data has suspicious maxima")
elif numpy.sum(data_min) == 0:
else:
print("Seems Ok")

files = glob.glob('./data/inflammation-*.csv')
files.sort()
for f in files:
plot_inflammation(f)
check_data(f)

This data has suspicious maxima
This data has suspicious maxima