Reputation: 21
The falling code is giving me the results I want but it keeps giving me the same error and the program doesn´t complete.
totalIdadesM = 0
totalIdadesH = 0
countM = 0
countH = 0
with open("info.txt", "r") as infoFile:
for line in infoFile:
if line[1] == "M":
for line in infoFile:
dados = line.split("=")
print(dados)
idade, peso = dados[1].split(",")
print(idade)
print(peso)
if idade.isdigit():
totalIdadesM += int(idade)
countM += 1
print(countM)
def calcMedia(total, num):
media = total / num
return media
And that's the error
['Ana', '24,55\n']
24 55
['Ines', '30,60\n']
30 60
['Sofia', '18,49\n']
18 49
['Carla', '44,64\n']
44 64
['\n']
Traceback (most recent call last): File "ex4.1.py", line 13, in idade, peso = dados[1].split(",") IndexError: list index out of range
The input is like this:
[Mulheres] Ana=24,55 Ines=30,60 Sofia=18,49 Carla=44,64
[Homens] Joao=20,75 Tiago=55,80 Quim=59,69
Upvotes: 0
Views: 68
Reputation: 44828
Your code's hitting an empty line. You can skip all empty lines with this:
for line in infoFile:
line = line.strip()
if not line: # empty line
continue # skip the body and go staring to next iteration
dados = line.split("=")
...
One thing I'm not sure about is why you're iterating over infoFile
twice. When you're iterating, you're reading from it, and here, for example, the first line will be skipped:
for line in infoFile:
# read first line
if line[1] == "M":
for line in infoFile:
# first line has already been read, so read the second line,
# thus skipping the first one altogether
...
# the loop will be exited when there'll be no more data to read
# so the outer loop will terminate since there's nothing to iterate over anymore
Upvotes: 1