Skip to content

Commit c9e48ff

Browse files
committed
Update after 3rd Python coding session
1 parent 1b74bc6 commit c9e48ff

1 file changed

Lines changed: 154 additions & 10 deletions

File tree

src/PythonBasics.py

Lines changed: 154 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,14 @@
255255

256256
# match - cases are an alternative control structure that is more efficient
257257
# when it comes to matching single strings
258+
259+
weathering_grades = {1: 'fresh',
260+
2: 'slightly weathered',
261+
3: 'moderately weathered',
262+
4: 'highly weathered',
263+
5: 'extremely weathered',
264+
6: 'residual soil'}
265+
258266
DRILLING_ID = 'D_06'
259267

260268
match DRILLING_ID:
@@ -443,32 +451,168 @@
443451

444452

445453

446-
447-
448454
###########################
449455
# session 3 on 17. September 2025
450456
###########################
451457

452-
# 1. repetition
453-
454458
### functions
455459

460+
# functions are created with the "def" keyword and have to have a name and a
461+
# "body" in brackets after the name
462+
463+
def hello_world_function(): # # basic printing function
464+
print('Hello World!')
465+
466+
467+
# functions need to be executed like this to run
468+
hello_world_function()
469+
470+
# defining the function
471+
def custom_addition(a, b, print_result = False):
472+
'''This is a custom addition function that computes the result of a + b'''
473+
result = a + b
474+
475+
if print_result is True:
476+
print(f'the result of the addition is: {result}')
477+
else:
478+
pass
479+
return result
480+
481+
# using the function
482+
output = custom_addition(30, 20, print_result=True)
483+
484+
print(output)
485+
456486
# Exercise 10
457487

488+
def custom_mean(numbers):
489+
'''the custom mean function takes a list of numbers and computes the
490+
average value'''
491+
result = sum(numbers) / len(numbers)
492+
print(f'mean value: {round(result, 2)}')
493+
return result
458494

459-
### coding style, Zen of Python
460495

496+
def custom_median(numbers):
497+
numbers = sorted(numbers)
461498

462-
###########################
463-
# session 4
464-
###########################
499+
if len(numbers) % 2 == 0: # in case of an even list
500+
mid_upper = int(len(numbers) / 2) # first we get the upper index
501+
mid_lower = mid_upper - 1 # then we get the lower index
502+
median = (numbers[mid_upper] + numbers[mid_lower]) / 2
503+
else: # in case of an uneven list
504+
mid = int(len(numbers) / 2)
505+
median = numbers[mid]
506+
507+
print(f'median value: {round(median, 2)}')
508+
return median
509+
510+
511+
def custom_variance(numbers, mean):
512+
sum_list = []
513+
514+
for x_i in numbers:
515+
sum_list.append((x_i - mean)**2)
516+
517+
sum_of_sum_list = sum(sum_list)
518+
519+
variance = sum_of_sum_list / len(numbers)
520+
521+
print(f'variance value: {round(variance, 2)}')
522+
return variance
523+
524+
525+
def custom_std(var):
526+
standard_deviation = var**0.5
527+
print(f'standard deviation: {round(standard_deviation, 2)}')
528+
return standard_deviation
529+
530+
531+
# compute the mean value, the median, the variance and the standard deviation
532+
# for that list:
533+
c = [1, 2, 3, 1, 3, 3, 2, 1, 4, 6, 4, 1]
534+
535+
536+
# mean
537+
mean_value = custom_mean(c)
538+
# median
539+
median_value = custom_median(c)
540+
# variance
541+
variance_value = custom_variance(c, mean_value)
542+
# standard deviation
543+
std = custom_std(variance_value)
465544

466545

467546
### modules, code environments, module documentation
468547

548+
# we us modules with using the "import" keyword and can also abreviate them in
549+
# the same row
550+
551+
# modules should be imported ontop of a script
552+
import matplotlib.pyplot as plt
553+
import numpy as np # numpy is short for "numerical python" and a math module
554+
import pandas as pd
555+
556+
# numpy works based on arrays and is much faster than classical loops
557+
exemplary_array = np.array([[1, 2, 3, 4, 5],
558+
[1, 2, 3, 4, 5]])
559+
560+
# the shape of the array can be queried and individual columns / rows accessed
561+
print(exemplary_array.shape)
562+
print(exemplary_array[:, 1])
563+
print(exemplary_array[1, :])
564+
565+
# number generation
566+
print(np.arange(start=10, stop=30, step=4))
567+
print(np.linspace(start=2, stop=5, num=5))
469568

470569
# exercsie 11
570+
numbers = [1, 2, 3, 1, 3, 3, 2, 1, 4, 6, 4, 1]
571+
572+
print(f'mean value: {round(np.mean(numbers), 2)}')
573+
print(f'median value: {round(np.median(numbers), 2)}')
574+
print(f'variance value: {round(np.var(numbers), 2)}')
575+
print(f'std value: {round(np.std(numbers), 2)}')
576+
577+
# matplotlib example
578+
579+
# let's create some random numbers
580+
581+
N_NUMBERS = 1000
582+
583+
584+
rng = np.random.default_rng()
585+
586+
# exemplary variables of different statistical distributions
587+
x = rng.uniform(0, 5, N_NUMBERS)
588+
y = rng.exponential(2, N_NUMBERS)
589+
z = rng.normal(2.5, 1, N_NUMBERS)
590+
591+
time = np.arange(0, N_NUMBERS) # seconds
592+
593+
# plotting
594+
fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(10, 5))
595+
596+
ax[0].hist(z, edgecolor='black', bins=60, density=True, zorder=30, alpha=.5,
597+
label='normal', color='forestgreen')
598+
ax[0].hist(x, edgecolor='black', bins=60, density=True, zorder=30, alpha=.5,
599+
label='uniform')
600+
601+
ax[0].legend()
602+
ax[0].set_xlabel('random numbers')
603+
ax[0].set_ylabel('number of datapoints')
604+
ax[0].grid(alpha=0.5, zorder=10)
605+
606+
ax[1].plot(time, z, label='normal', color='forestgreen', alpha=.5)
607+
ax[1].plot(time, x, label='uniform', alpha=.5)
608+
609+
ax[1].legend()
610+
ax[1].set_xlabel('time')
611+
ax[1].set_ylabel('random numbers')
612+
ax[1].grid(alpha=0.5)
471613

472-
# exercsie 12
614+
plt.tight_layout()
615+
plt.savefig('test.jpg', dpi=220)
473616

474-
# exercsie 13
617+
# there are more complex alternatives to plot generation that allow to be more
618+
# creative. E.g.: gridspec

0 commit comments

Comments
 (0)