user3358965
user3358965

Reputation: 25

Adding Up Numbers From A List In Python

basically i'm trying to complete a read file. i have made the "make" file that will generate 10 random numbers and write it to a text file. here's what i have so far for the "read" file...

def main():
    infile = open('mynumbers.txt', 'r')
    nums = []
    line = infile.readline()

    print ('The random numbers were:')
    while line:
        nums.append(int(line))
        print (line)
        line = infile.readline()

    total = sum(line)  
    print ('The total of the random numbers is:', total)

main()

i know it's incomplete, i'm still a beginner at this and this is my first introduction to computer programming or python. basically i have to use a loop to gather up the sum of all the numbers that were listed in the mynumbers.txt. any help would be GREATLY appreciated. this has been driving me up a wall.

Upvotes: 0

Views: 565

Answers (3)

Tim Pietzcker
Tim Pietzcker

Reputation: 336478

You don't need to iterate manually in Python (this isn't C, after all):

nums = []
with open("mynumbers.txt") as infile:
    for line in infile:
        nums.append(int(line))

Now you just have to take the sum, but of nums, of course, not of line:

total = sum(nums)

Upvotes: 2

nneonneo
nneonneo

Reputation: 179717

The usual one-liner:

total = sum(map(int, open("mynumbers.txt")))

It does generate a list of integers (albeit very temporarily).

Upvotes: 1

Amit
Amit

Reputation: 20516

Although I would go with Tim's answer above, here's another way if you want to use readlines method

# Open a file
infile = open('mynumbers.txt', 'r')

sum = 0
lines = infile.readlines()
for num in lines:
    sum += int(num)

print sum

Upvotes: 0

Related Questions