-1

Question:

  1. In main, create an empty list.
  2. Open the file named scores.txt and use a while loop that can detect the end of file to read the scores, and add them to the list and then close the file.
  3. Call the showscores function with the list of scores as sole argument.
  4. Inside the showscores function, process the list of scores.
  5. Print out the average score accurate to two decimal places.

This is scores.txt which contains a list of 5 numbers. The numbers in the file are list vertically like so:

                                          86

                                          92

                                          77

                                          83

                                          96

I have the below code now, but keep getting thiese errors:

line 19, in main()

line 17, in main showscores(scores)

line 2, in showscores sum_scores = sum(scores)

TypeError: unsupported operand type(s) for +: 'int' and 'str'

def showscores(scores):
sum_scores = sum(scores)
average = float(sum_scores // len(scores))
print ("The scores are: " + str(scores))
print ("Average score: " + str(average))


def main():
scores = []
scores_file = open("scores.txt", 'r')
line_list = list(scores_file.readlines())
i = 0
while i < len(line_list):
    scores.append(line_list[i])
    i += 1
scores_file.close()
showscores(scores)

main()
John Finger
  • 39
  • 2
  • 7
  • 2
    Read the relevant parts about file I/O: http://www.tutorialspoint.com/python/python_files_io.htm – sshashank124 May 18 '15 at 05:31
  • Did you google the resulting exception? I'm sure there are plenty other people who had the same issue than you, including on this website and got their issue solved. (Don't become a Help Vampire!!) Basically, as the exceptions says you are trying to addition a string to a int. You first need to cast that string to an int (and maybe formatting it before being able to do so). On which line is that exception raised? Shouldn't happen with the piece of code you copied here. – jeromej May 18 '15 at 18:54
  • Says line 7, in showscores sum_scores = sum(scores) line 28, in main showscores(scores) line 30, in main() have been googling and researching error, but the changes I make don't work or are not needed according to what I see... – John Finger May 18 '15 at 19:21
  • Yeah I have no idea...been searching past two hours, and can't figure it out... – John Finger May 18 '15 at 21:23
  • Hello, this is probably no longer relevant for you but if you look at the error you have, it should also give you the stacktrace and the method it originated from and my best bet is that it comes from the `sum` method. You can't sum strings: you'll first have to turn the strings into int. Instead of adding the whole line to the list, you need cast it into an int using `int(line_list[i])` (before that, you may need to remove trailing/leading blank spaces or it will throw... I'll let you Google it!) – jeromej Dec 12 '22 at 08:41

4 Answers4

7

No one here is really helping him. It is pretty obvious that OP just started learning programming and is having some issue figuring it out. (Right?)

Giving him all made solutions just to get some rep won't do.

I think OP is faced with an exercise or homework and has defined steps to follow.

OP, it is hard at first but it is going to be ok.

Describing the parts that seem to cause you more troubles:

  • You need to open the file, for this, you can read the link that sshashank124 gave you ( http://www.tutorialspoint.com/python/python_files_io.htm ).
  • The while expects from you to read the text file line by line (that is why you need a while loop, to repeat the same action for each line). For each line, add its content to the list you previously created.
  • Give that list to the function showscores (that you need to code as well), and if I understand the directions you received, you "process" the data there. Because what is in your current list? A string of each line. Process it so you turn it into, more practical, actual numbers.
  • From there, you can now calculate what has been asked to you (average, etc) and display it.

For examples of code, check the other answers. Even though they might trouble you because they, IMHO, don't seem "noob friendly". Don't forget to use for favorite search engine if you get any issue, read the documentation, etc.

EDIT: As you seem to specifically struggle with the while loop. Here is a small code showcasing it.

Before please check out that small tutorial to understand the basic behind it: http://www.afterhoursprogramming.com/tutorial/Python/While-Loop/

So instead of the magic for loop that does it all for you, here is how you'd do it using while:

def main():
    scores = []

    scores_file = open("path to scores.txt", 'r')

    line_list = list(scores_files.readlines())

    i = 0
    while i < len(line_list):
        scores.append(line_list[i])
        i += 1

    showscores(scores)
jeromej
  • 10,508
  • 2
  • 43
  • 62
  • Thanks for the input, the problem I am having is with the while loops. I just cannot seem to understand them in regard to this. I understand most of the other parts, though. – John Finger May 18 '15 at 17:45
  • That link did a bit, but now I just keep getting an error when trying to run it. I changed "path to scores.txt to just scores.txt, thats what I think i was supposed to do right? and then I get an error that name f is not defined. – John Finger May 18 '15 at 18:22
  • @JohnFinger My fault. Forgot to change that variable name. Make sure to understand the codes you are running, it will help you greatly later. Cheers. **EDIT:** you might want to close that file at the end of the loop too, as per asked and because it is better to do so anyway! – jeromej May 18 '15 at 18:25
  • Just as you said that I saw that lol. Thanks. Now I am getting an error: FileNotFoundError: [Errno 2] No such file or directory: 'scores.txt' for some reason.. – John Finger May 18 '15 at 18:27
  • @JohnFinger Make sure that you are in the right directory. Either that your script and scores.txt are in the same directory (be sure to check that the filename is spelled properly, and watch out for the case if you are not using Windows) or, if you launch Python from the console, be sure to be in the directory where scores.txt is before to run the program. – jeromej May 18 '15 at 18:29
  • Was not in same directory, dumb mistake on my part. Keep getting new errors though...now its TypeError: unsupported operand type(s) for +: 'int' and 'str'. Should I edit my post with what I have no fully? – John Finger May 18 '15 at 18:34
  • I posted what I have fully in my orignal question. – John Finger May 18 '15 at 18:40
0

I have tried this and it works:

def showscores(scores):
    sum_scores = sum(scores)
    average = float(sum_scores // len(scores))
    print ("The scores are: " + str(scores))
    print ("Average score: " + str(average))



def main():
    f = open("PATH TO YOUR FILE", 'r')
    content = list(f.readlines())
    scores = []
    for x in content:
        scores.append(int(x.replace(" ", "")))

    showscores(scores)

main()

Hope this works for you

AkaiShuichi
  • 144
  • 1
  • 1
  • 9
  • Where is the "while loop" used in this? Just trying to understand everything. Thanks. – John Finger May 18 '15 at 07:11
  • 1
    @JohnFinger A `for` loop is really just a fancy `while` loop. They are more appreciated in Python, but learners are often taught about `while` loop first to help them improve their logic skill. When using a `while` loop, you have to take care of the index yourself (often `i` that you increment at the end of each iteration), `for` does the job for you. With some knowledge/understanding, you can easily rewrite the `for` loop into a `while` loop. Especially since, if you have a homework or something like that, you are expected to use `while` and not something else (yet). Good luck. – jeromej May 18 '15 at 08:12
  • Thats is what I have been trying to do now, and cannot seem to figure out even where to start to edit it. – John Finger May 18 '15 at 17:46
0

Solution with Exception Handling.

Code:

import os

def showscores(scores):
    """ average """
    #- Get Total sum from the scroes list by sum in-build function. 
    total = sum(scores)
    print "Debug 4:", total
    #- Get average and handle dividing by zero  exception. 
    try:
        avg = total/float(len(scores))
    except ZeroDivisionError:
        avg = 0.0

    #- Print result.
    print "average of scores is= %.2f"%avg

    return

def main():
    """ Get Scores from the file."""

    file_name = "scores.txt"
    #- Check file is exists or not.
    if not os.path.isfile(file_name):
        print "Input file is not found."
        return []

    scores = []
    #- Read file content.
    with open(file_name, "rb") as fp:
        #- Iterate file upto EOF line
        while True:
            line = fp.readline()
            if not line: 
                break
            #- Type Casting because line is string data type.
            try:
                scores.append(int(line.strip()))
            except ValueError:
                print "Exception during Type Casting.- Input %s"%line

    return scores


if __name__=="__main__":
    scores = main()
    showscores(scores)

Output:

Exception during Type Casting.- Input 

Exception during Type Casting.- Input 

Exception during Type Casting.- Input 

Exception during Type Casting.- Input 

Debug 4: 434
average of scores is= 86.80

Use with statement and map function:

#- Read file content.
with open(file_name, "rb") as fp:
    content = fp.read()

#- Get all numbers from the file content by RE and map.
scores = map(int, re.findall("\d+", content))


return scores
Vivek Sable
  • 9,938
  • 3
  • 40
  • 56
  • Where is the "while loop" used in this? Just trying to understand everything. Thanks. – John Finger May 18 '15 at 07:23
  • @JohnFinger: ok , now check. also ref- http://stackoverflow.com/questions/15599639/whats-perfect-counterpart-in-python-for-while-not-eof – Vivek Sable May 18 '15 at 07:54
  • Is there any easier way to change the for loop that I edited in my question to a while loop in that? I appreciate your help, but the answer is a little bit too complicated for me to understand yet. Thanks again. – John Finger May 18 '15 at 17:44
0

This has been completed. This is what ended up working:

def showscores(scores):
    sum_scores = sum(scores)
    average = float(sum_scores // len(scores))
    print ("The scores are: " + str(scores))
    print ("Average score: " + str(average))


def main():
    scores = []
    scores_file = open('scores.txt', 'r')
    line_list = list(scores_file.readlines())
    scores_file.close()
    i = 0
    while i < len(line_list):
        scores.append(int(line_list[i].strip()))
        i += 1

    showscores(scores)

main()
John Finger
  • 39
  • 2
  • 7