Jump to content


Photo

Chapter 4


  • Please log in to reply
3 replies to this topic

#1 bruno1067

bruno1067

    New Member

  • Members
  • Pip
  • 4 posts
  • Gender:Male

Posted 24 June 2014 - 12:44 PM

Hi,

I can't find out why, but Phyton is only finding the index[0] from my array... Here is my code:

result_f = open("results.txt")

for line in result_f:
    scores = []
    (name, score) = line.split()
    scores.append(score)

result_f.close

print(scores[0])
print(scores[1])
print(scores[2])

But Python keeps returning:

>>>
8.31
Traceback (most recent call last):
File "/Users/Bruno/Documents/Surf.py", line 12, in <module>
print(scores[1])
IndexError: list index out of range


Tried the code from the labs file, but I'm getting the same error. What's happening?

#2 bruno1067

bruno1067

    New Member

  • Members
  • Pip
  • 4 posts
  • Gender:Male

Posted 24 June 2014 - 12:59 PM

Hm... I got the scores on order by putting logic on paper... But I still want to learn what the chapter says...

result_f = open("results.txt")

highest_score = 0
second_high = 0
third_high = 0

for line in result_f:
    (name, score) = line.split()
    
    if float(score) > float(highest_score):
        third_high = second_high
        second_high = highest_score
        highest_score = score

result_f.close


print("The Results are: ")
print(highest_score, second_high, third_high)


#3 bruno1067

bruno1067

    New Member

  • Members
  • Pip
  • 4 posts
  • Gender:Male

Posted 25 June 2014 - 02:31 AM

I GOT IT!!!

I just had to put the array/list outside the loop, because everytime the loop iterated, it cleaned my array when it got to the line
scores = []
. And then, every new score was being assigned to index
[0]
again. :D

Phew...

#4 bruno1067

bruno1067

    New Member

  • Members
  • Pip
  • 4 posts
  • Gender:Male

Posted 25 June 2014 - 02:37 AM

And by the way, my logic above is wrong




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users