1

For this function I am supposed to read a file with 12 random numbers. Then I am supposed to output the numbers 1 per line and finally the program is supposed to separate the even numbers and the odds then add them up and display their totals. The problem here is that even though I am getting printing of the numbers fine, the total function in the end is messing up and giving incorrect totals.

def main():

    infile = open('numbers.txt','r')

    line1 = infile.readline()
    line2 = infile.readline()
    line3 = infile.readline()
    line4 = infile.readline()
    line5 = infile.readline()
    line6 = infile.readline()
    line7 = infile.readline()
    line8 = infile.readline()
    line9 = infile.readline()
    line10 = infile.readline()

    line1 = line1.rstrip('\n')
    line2 = line2.rstrip('\n')
    line3 = line3.rstrip('\n')
    line4 = line4.rstrip('\n')
    line5 = line5.rstrip('\n')
    line6 = line6.rstrip('\n')
    line7 = line7.rstrip('\n')
    line8 = line8.rstrip('\n')
    line9 = line9.rstrip('\n')
    line10 = line10.rstrip('\n')

    print(line1)
    print(line2)
    print(line3)
    print(line4)
    print(line5)
    print(line6)
    print(line7)
    print(line8)
    print(line9)
    print(line10)

    line = infile.readline()

    total = 0
    evenTotal = 0
    oddTotal = 0

    while line != '':
        total += int(line)
        if int(line) % 2 == 0:
            evenTotal += int(line)
        else:
            oddTotal += int(line)
        line = infile.readline()

    print("=======================================")
    print('The total for the even numbers is', evenTotal)
    print("=======================================")
    print('The total for the odd numbers is', oddTotal)

    infile.close()
main()

Here's are the contents from the file

47
64
67
40
91
98
82
2
42
84
48
96

I am only getting 0 for both the totals somehow.

Can someone help with this?

5
  • 3
    Wow you need to learn loops (see e.g. docs.python.org/2/tutorial/controlflow.html). But you're great in Modern Family! Commented Feb 19, 2015 at 22:06
  • I believe you have read all the lines in the file when you're setting line1 = ..., line2 = ... meaning line equals nothing. You could read the lines inside the while loop, strip the newline and add the number to evenTotal/oddTotal Commented Feb 19, 2015 at 22:08
  • There was a very similar (meaning almost exact) question asked couple of days ago. Is there some kind of class running somewhere? Read the responses on that question. They deal with a lot of little things that are bothering you as well and could easily help you too! Commented Feb 19, 2015 at 22:08
  • 1
    @ljetibo In the US anyways a new school semester recently started :) Commented Feb 19, 2015 at 22:09
  • 1
    Unrelated, since you're also maintaining a total you don't need both evenTotal and oddTotal since oddTotal == total - evenTotal :) Commented Feb 19, 2015 at 22:09

4 Answers 4

4

The file object returned by open maintains a pointer to where you are currently in a file. Each time you call infile.readline() it is advancing that pointer to the next line.

Because in the process of testing your code you're reading each line (and printing it) in advance, when you get to the later code that counts the values of the lines your file has already reached the end and will not magically go back to the beginning of the file.

You can either reopen the file, or more simply use infile.seek(0) to return the file pointer to the beginning of the file.

Sign up to request clarification or add additional context in comments.

Comments

4

You have two errors in your code,

  1. first you read your file line by line, reaching the end of file, and later you try to read further... that's impossible, you have to rewind your file, as explained in Iguananaut's answer.

  2. your approach is, well, unusual... in general files are not read so explicitly, line1, line2, etc --- you want to be more generic so that your solution of a programming problem results more general.

Of course there are a number of things you don't know about the manner Python deals with files, as the only thing you appear to know is the .readline method, that you abused a little. One really important thing about files is that file objects (what is returned by a open) are iterables, that is you can use them in a for loop (e.g., line 5 below), and the object that you have to deal with in every iteration is a line of text. That said, you can organize your code as follows

# initialize your accumulators
odds = 0 ; evens = 0

# read lines from your file simply iterating on the file object!
for line in open('numbers.txt'):

    # the int function ignores the white space, no need to strip
    n = int(line)
    % now you can print n
    print(n)
    # with an if...else... we update the accumulators
    if n%2:     # n is odd
        odds += n
    else:
        evens += n
    # we have read a line, converted in an integer, printed it,
    # we updated the sums, we have done everything, hence

# we dedent the code, meaning that we are out of the loop
total = evens+odds
print("The sum of all even numbers is", evens)
...

Comments

2

You should learn to use list comprehensions or loops instead...

infile = open('numbers.txt','r')
numbers = [int(line) for line in infile]

evens = [num for num in numbers if num % 2 == 0]
odds = [num for num in numbers if num %2 == 1]

You should be able to do the rest with the code you have, however note that sum([1,2,3,4,5]) returns 15!

2 Comments

I am going to look into what you said for sure. Thanks!
All good advice in practice to be sure, but if this is a homework assignment it might not be accepted, depending on what the parameters of the assignment are.
2

@Iguananaut provided you with an answer to your issue. Here's a solution to the problem stated in the question, to show how it can be done.

For this function I am supposed to read a file with 12 random numbers. Then I am supposed to output the numbers 1 per line and finally the program is supposed to separate the even numbers and the odds then add them up and display their totals.

total = [0, 0] # even, odd
with open('numbers.txt') as file:
    for n in map(int, file): # read integers from the file, 1 per line
        print(n) # "output the numbers 1 per line"
        total[n & 1] += n  # "separate the even .. and the odds then add them"
print("Even total: {}, odd total: {}".format(*total)) # "display their totals"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.