142k views
4 votes
A file named numbers.txt contains an unknown number of lines, each consisting of a single integer. Write some code that computes the sum of all these integers, and stores this sum in a variable name sum. *PYTHON*

A file named numbers.txt contains an unknown number of lines, each consisting of a-example-1

1 Answer

0 votes

f = open("numbers.txt", "r")

lst = [int(x) for x in f.read().splitlines()]

sum = 0

for x in lst:

----sum += x

I had to add the four dashes to maintain the structure of my code. You can replace them with spaces. Also, I wouldnt recommend having a variable named sum because python has a built in function named sum. You can test this code by putting print(sum) at the end of the code.

User Kien Chu
by
7.9k points