I’m new in programming, I really need a detailed explanation of the following code, in particular I need to know:
- What are that square brackets after the variables, why are used?
- What is open?
- What is readlines? Is it a method? If yes how does it works?
- what is happening here sex = int(float(l.split()[2])), I need a translation.
- What is close? Is it a method? If yes how does it works?
So, in short, I need a commentary that explains what’s happening here. I will be really gratfull, thanks.
Exercise:
The file ex1_1.txt includes data for a set of patients. The data are organized into rows with the following format: x time sex, where x is an experimental measurement, time is when the measurement was taken (in seconds), and sex is 0 for male and 1 for female.
- Read the file line by line, and print each line
- For each line, define the values x, t, and sex equal to the values in the 1st, 2nd and 3rd column respectivelly. Define x and t as floating values, and sex as an integer value
- Define the lists X, T, and SEX including all the values read from the file
- Use the function average define above to calculate the mean of X
- Compute the mean of X separately for men and women
X = #these are square brackets
T =
SEX =
fin = open(‘ex1_1.txt’,‘r’)
for l in fin.readlines():
print(l)
x = float(l.split()[0])
t = float(l.split()[1])
sex = int(float(l.split()[2]))
X.append(x)
T.append(t)
SEX.append(sex)
fin.close()
print('Average: ',average(X))
X_male =
i = 0
while i < len(X):
if SEX[i] == 1:
X_male.append(x)
i = i + 1
print('Male average: ',average(X_male))