I'm fairly new to Python and am exploring how to fix functions and make code 'more effective and readable'. As a first step, I would want to try to make shorter snippets of code here - for example by dividing it into more functions.
I would also appreciate further improvements regarding possible errors I might stumble upon.
No need for imports.
The code is supposed to take values from a batch on a x- and y-position in the unit circle.
Example input:
1, 0.1, 0.1, 10 1, 0.2, 0.2, 15 2, 1.2, 1.2, 20 2, 0.5, 0.5, 25 Several values can be used in a batch. If x² + y² > 1, it will not take that value into account when calculating the average of a batch. If no values in a batch are used, no average is calculated (avoiding division by zero).
def a(): while True: data = dict() # Or data = {} try: filename = input('Which data file? ') with open(filename, 'r') as h: for line in h: try: four_vals = line.split(',') batch = four_vals[0] if not batch in data: data[batch] = [] data[batch] += [ (float(four_vals[1]), float(four_vals[2]), float(four_vals[3]))] except ValueError: print('Some data are not integers in batch',batch,", line", line,"\nThose values are not taken into account\n" ) except IOError: print('No such file or directory was found, the written file can not be opened.'"\n"'Look through misspellings or that the written file is actually in the pathway.') continue return data def b(): data = a() data = dict(sorted(data.items())) return data def c(): data = b() for batch, sample in data.items(): try: #len(sample) > 0: n = 0 # antal prov startar på 0 x_sum = 0 # summan startar på 0 for (x, y, val) in sample: circle = x ** 2 + y ** 2 if circle <= 1: x_sum += val n += 1 else: print(batch,"\t","Outside of the unit circle,", circle,">1") average = x_sum / n print(batch, "\t", average) except ZeroDivisionError: print(batch, "\tNo data")