O'Reilly Forums: Chapter 4: High_Score2.py Prints Last Line Of Results.txt - O'Reilly Forums

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Chapter 4: High_Score2.py Prints Last Line Of Results.txt

#1 User is offline   M.Hoes 

  • New Member
  • Pip
  • Group: Members
  • Posts: 8
  • Joined: 21-December 12

Posted 25 December 2012 - 02:54 AM

Hi, Im havingproblems with high_score2.py on page 125. Instead of printing the highest score, it prints the last line of the results.txt file. No matter what I put as the last line of that file, thats the score that gets printed. Here's my program and my results.txt :

highest_score = 0
result_f = open("results.txt")
for line in result_f:
(name, score) = line.split()
if float(score) > highest_score:
highest_score = float(score)
result_f.close()
print("The highest score was: ")
print(score)

Johnny 8.65
Juan 9.12
Joseph 8.45
Stacey 7.81
Aideen 8.05
Zack 7.21
Aaron 8.31

This post has been edited by M.Hoes: 25 December 2012 - 02:59 AM

0

#2 User is offline   #TM# 

  • Active Member
  • PipPip
  • Group: Members
  • Posts: 16
  • Joined: 10-December 12

Posted 25 December 2012 - 05:25 AM

JUST WATCH OUT WHAT YOU ARE PRINTING !!
YOU ARE NOT PRINTING THE HIGHEST SCORE!!

highest_score = 0                                  # initialisation of variable "highest_score"
result_f = open("results.txt")                 # file opened and assigned to file handler
for line in result_f:                                   # for each line in file handler
    (name, score) = line.split()               # split each line and assign to two varibles.
    if float(score) > highest_score:        # optimisation for getting highest score
        highest_score = float(score)
result_f.close()                                        # file closed.
print("The highest score was: ")           
print(highest_score)                              # printing highest score. 

this last line is the problem in your program, instead of displaying the value stored in variable "highest_score", it displays the value stored in variable "score".

just check it out !! B)
:)

This post has been edited by #TM#: 25 December 2012 - 05:30 AM

0

#3 User is offline   M.Hoes 

  • New Member
  • Pip
  • Group: Members
  • Posts: 8
  • Joined: 21-December 12

Posted 25 December 2012 - 05:41 AM

Ooops ! I dont understand how I possibly could have missed that...

Thanks ! It now runs as expected!
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users