• Series of integers : Python program to read all of the number stored

    Adelaid Member

    Assume that a file containing a series of integers is named numbers.txt and exist on the computer’s disk. write a program that reads all of the number stored in the file and calculates their total.

    This is what i have and i need help im stuck.

    #This program calculates the total in numbers contained in the file
    #numbers.txt

    # reads all the lines in a numbers file

    def main():
    numbers= open(r'c:\numbers.txt', 'r')

    for line in numbers:

    print(line)
    #close the file
    numbers.close()
    
    #call main fucntion
    main()
    
  • SapnaVishwas Member

    Your code is alright except it didn’t have the addition operation (since that’s what you want to do). Firstly, you must declare a variable (lets call it sum and set it to 0).
    Then you will want to iterate the lines inside the text file, you can use for function to iterate it, and at the same time you will add the number line by line into variable sum. Don’t forget to change the number in the text file into integer since python will treat it as string instead of integer and you can’t perform addition.

    Lastly you need to return the variable so you can call the result later.

    #This program calculates the total in numbers contained in the file
    #numbers.txt
    
    def main():
       n = open(r'C:\numbers.txt', 'r')
       sum = 0
       for line in n:
       sum += int(line)
       return sum
       n.close() #close the file
    
    #call main function
    total = main()
    print total
    
  • Amit Member

    Assuming each number is on it’s own line, read each line, parse it as an integer, and add to the sum.

    sum = 0
    for line in numbers:
    sum += int(line)
    print(sum)
    
Viewing 2 reply threads
  • You must be logged in to reply to this topic.
en_USEnglish