-1

I am attempting to open a file with python in order to take the averages off of a file input.txt. After the averages are taken, they then must be displayed after each person's name such as

<student>'s score is <avg> bacons.

We have not yet gone over this in class, so I'm not really sure what I'm doing. I assume we're supposed to be using a loop, but I'm not exactly sure how I would implement it.

This is the code, which keeps returning that avg as invalid syntax:

def main():
    inFile = open("input.txt","r")
    numVals = int(inFile.readline())
    name = inFile.readline()
    number = float(int(inFile.readline().split())
    avg = float(int(number[0]* .3 + number[1]* .1 + number[2]* .6))
    print("name[0 , len(name)]'s Score is",avg,"bacons.")
    inFile.close()

main()

The input file contains

5
Amelia 
90 100 75 
George 
87 90 90 
Adam 
100 80 85 
Jenny
75 80 90 
Carl 
86 87 88 

Any help on this would be appreciated. I have no idea what to do.

4

2 に答える 2

3

Your first problem is this line:

number = float(int(inFile.readline().split())

You have four (s, but only three )s.

Therefore, Python is expecting the expression to continue on the next line, but it sees an =, which can't appear in the middle of an expression, so it raises a SyntaxError.

When you get a SyntaxError on a line that looks perfectly fine, there are two good things to try.

First, break that line up into smaller pieces, type those smaller pieces into the interactive interpreter, etc.

Second, once you're sure that line is fine, look at the line above it and count the parentheses (and brackets and braces). A good editor makes this much easier to spot—or just type the line into the interactive interpreter; if you haven't closed all your parentheses, it'll give you a ... instead of >>>, meaning it's waiting for you to finish the previous line, instead of waiting for a whole new line.


Once you get past that, you're going to get a ValueError, because you're trying to call int on a list of three strings that you got back from readline. That doesn't work; you have to call int on each one. So, instead of this:

numbers = float(int(inFile.readline().split()))

Do this:

numbers = [float(int(number)) for number in inFile.readline().split()]

If you haven't learned list comprehensions yet, you'll have to do that with a loop instead. For example:

numbers = inFile.readline().split()
for n in range(len(numbers)):
    numbers[n] = float(int(numbers[n]))

By the way, I'm not sure why you're doing float(int(…)). If you want to truncate them all to integer values, you don't need the float here—multiplying an integer by .3 works just fine. If you want to keep any decimal part, you don't need the int. So, just use one or the other.

And you do the same thing on the next line:

avg = float(int(number[0]* .3 + number[1]* .1 + number[2]* .6))

The result of number[0]* .3 + number[1]* .1 + number[2]* .6 is a float, like 89.1 for George. You then convert that into an int, which will give you 89. You then convert it back to float, getting 89.0. I can't imagine this is what you want—you probably want the un-converted 89.1, or maybe the truncated 89 as an int, not 89.0 as a misleading float.


Also, the way you're printing things out is pretty strange, and I'm not sure what it's supposed to do:

print("name[0 , len(name)]'s Score is",avg,"bacons.")

This will print something like:

name[0 , len(name)]'s Score is 89.0 bacons.

If you want to print the value of a variable, don't put it in quotes:

print(name, "'s Score is",avg,"bacons.")

But whatever you're trying to do with that 0 and len(name)… well, I don't know what you're trying to do, so I can't explain how to do it.

Anyway, this will print:

George 's Score is 89.0 bacons.

You probably don't want that space after George, right? The best way around this is to use string formatting:

print("{}'s Score is {} bacons'".format(name, avg))

If you haven't learned that yet, honestly, I think the best thing is to just deal with the extra space, or maybe rewrite the sentence so it's not a problem:

print(name, 'has a score of', avg, 'bacons.')

Or, of course, learn it yourself before your teacher gets to it. It's not that complicated.


Finally, when you get past that, you're only reading one name and list of numbers, not numVals worth of them. To do that, you need a loop:

def main():
    inFile = open("input.txt","r")
    numVals = int(inFile.readline())
    for i in range(numVals):
        name = inFile.readline()
        # ... the rest of your code that happens for each player
    # ... the code that happens after all the players, like inFile.close()
于 2013-02-16T00:20:15.147 に答える
0

EDIT*** I figured it out in the end. My code didnt work for a multitude of reasons mostly b/c I didnt know how important indenting was

def main():

    inFile = open("input.txt","r")
    numVals = int(inFile.readline())


    for i in range(numVals):

        name = inFile.readline().replace("\n","")
        numbers = inFile.readline().split()
        avg = float(numbers[0])*.3 + float(numbers[1])*.1 + float(numbers[2])*.6
        print(name,'has a final score of',avg)


    inFile.close()
main()
于 2013-02-22T05:36:20.043 に答える