Hello all! I was able to make a program that writes random numbers to a file depending on how many the user requests. I now need to write a program that read those numbers...prints them... then at the end adds all the numbers from each line together and adds them. I think I probably am not using the for loop properly.
Here is what I have so far.. len shows 0 and so does the total.

def main():
    amount = 0.0
    total = 0.0

    infile = open('randomnumbers.txt', 'r')
    ##Read lines from file then print next line
    line = infile.readline()
    while line != '':
        num = line.rstrip('\n')
        print(num)
        line = infile.readline()
    ## Add numbers from lines together    
    for num in infile:
        amount = int(num)
        total = amount + amount
    print(total)
    #Show total number of numbers in file. 
    print(len(line))
    infile.close()

main()

Another instance of making it to difficult for my own good -.-

def main():

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

    #accumulator
    total = 0.0
    #line count
    count = 0

    #get values from file and print then total.
    for line in infile:
        number = float(line)
        print(number)
        count += 1

        total += number
    infile.close()
    print(count, total)

main()

Some hint,it's ok to use total += number as practice.
Here i do the same with build in sum().

"""
randomnumbers.txt-->
1 4 5
2 4 8
"""

with open('randomnumbers.txt') as f:
    print sum(float(i) for i in f.read().split()) #24.0

So this sum up all numbers in one go.
Split it up to show what's going on.

with open('randomnumbers.txt') as f:
    str_lst = f.read().split()
    print str_lst #--> ['1', '4', '5', '2', '4', '8']

    #Convert str_lst to integer or float
    lst = [int(i) for i in str_lst]
    print lst #--> [1, 4, 5, 2, 4, 8]

    #Sum up numbers in lst
    print sum(lst) #--> 24

    #Total numbers in file
    print len(lst) #--> 6

Not use sum().

lst = [1, 4, 5, 2, 4, 8]
total = 0.0
for numbers in lst:
    total += numbers

print total #--> 24.0

Edited 3 Years Ago by snippsat

This question has already been answered. Start a new discussion instead.