So, i was trying to read the score from the end. Instead of using
scores = game[-1]
i used
scores = game[1]
. However i got a new error
Error:
Traceback (most recent call last):
File "./hw2.py", line 25, in <module>
print(team_average('red_sox.txt'))
File "./hw2.py", line 20, in team_average
if (int(score[0]) - int(score[1])) > 0:
IndexError: string index out of range
And what do you get if you print out the values you are using for line 20??
for score in scores_list:
if (int(score[0]) - int(score[1])) > 0:
here you don't need the loop
for the first line the scores_list is ['7','5']
So i finally got the code right and below is my final code :
def team_average(filename):
numberOfGames = 0
soxWins = 0
try:
file = open(filename, 'r')
except:
print (filename, "Cannot be opened")
else:
for line in file:
numberOfGames += 1
game = line.split()
scores = game[-2]
if scores == 'Win':
soxWins += 1
average_win = int((soxWins/numberOfGames) * 100)
return average_win
team_average('xxxxxx')
print(team_average('red_sox.txt'))
I learned a lot just from this thread of course with your tremendous help. Below are some of the acquired knowledge:
- Troubleshoot the code using the print statement
- avoid the use of the exception any how and everywhere, it can hide errors.
- indentation issue
- Usage of the for loop
- Etc...
Thanks a lot gentlemen
Good that you solved it.
Some points,average is a confusing name when you calculate percentage
Do not use bare
except:
and return out when error occurred.
Eg:
def team_average(filename):
try:
file = open(filename)
except IOError as error:
return error
else:
numberOfGames = 0
soxWins = 0
for line in file:
numberOfGames += 1
game = line.split()
scores = game[-2]
if scores == 'Win':
soxWins += 1
win_percent = int((soxWins/numberOfGames) * 100)
return win_percent
print(team_average('red_sox.txt'))
Alternative way and a little more Pythonic could be:
with open('red_sox.txt') as file:
all_games = [line for line in file]
win = [game for game in all_games if 'Win' in game]
win_percent = len(win) / len(all_games) * 100
print(win_percent)