[Tutor] reading complex data types from text file

bob gailer bgailer at gmail.com
Thu Jul 16 23:08:46 CEST 2009


Chris Castillo wrote:
> *so far I have this and the format is what i want:*
> ------------------------------------------------------------------------------------------
> # Set all necessary variables
> name = None
> fileOut = open('outputFile.txt', 'w')
>
> total = 0
> averageScore = 0
> numofScores = 0
> score = 0
>
> # Header for output file
> fileOut.write("Bowling Report\n" + ("-" * 40) + "\n")
>
> # Iterate line by line through file to get names and their 
> corresponding scores
> for line in open('bowlingscores.txt', 'r'):
>   line = line.strip()
>   if line:
>     if line.isdigit():
>         score = int(line)
>         numofScores += 1
>         total += score
>        
>         averageScore = total / numofScores # Get average score
>        
>         # Decides where bowler stands compared to the average score
>         if score < averageScore:
>             score = "\tBelow average"
>         elif score > averageScore and score != 300:
>             score = "\tAbove average!"
>         elif score == 300:
>             score = "\tPerfect score!"
>     else:
>         name = line
>
>     # Checks to see if name and score have values
>     if name and score:
>         fileOut.write('%s\t%s\r\n' % (name, score))
>         name, score = None, None
>
>
> fileOut.close()
> ------------------------------------------------------------------------------------
> *the problem is that it's not comparing the first bowler's score to 
> the average score and the output file looks like this:
> *
> Bowling Report
> ----------------------------------------
> David    120
>
> Hector        Perfect score!
>
> Mary        Below average
> *
> is the logic in my if-elif statements wrong or is it just skipping the 
> first bowler's score?
> *

You must process all the scores before computing averages. This means 
saving each player's score.

Use a dictionary with the name as the key and the score as the value. 
Then go thru the dictionary to compute and report averages.


-- 
Bob Gailer
Chapel Hill NC
919-636-4239


More information about the Tutor mailing list