The Way to Programming
The Way to Programming
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()
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
Sign in to your account