Sarah Hyland
Sarah Hyland

Reputation: 267

Getting incorrect output from code in Python

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?

Upvotes: 1

Views: 474

Answers (4)

jfs
jfs

Reputation: 414079

@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"

Upvotes: 2

gboffi
gboffi

Reputation: 25023

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)
...

Upvotes: 4

Adam Smith
Adam Smith

Reputation: 54163

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!

Upvotes: 2

Iguananaut
Iguananaut

Reputation: 23296

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.

Upvotes: 4

Related Questions