Basically, this is my task. Extract numbers from a text file and then calculate the sum of them.
I wrote the code successfully and but it doesn’t work fine with 2 or more digit numbers and negative numbers. What should i do?
f = open('file6.txt', 'r') suma = 0 file = f.readlines() for line in file: for i in line: if i.isdigit() == True: suma += int(i) print("The sum is ", suma)
The sum is 2
In your case, you are going line by line first through the loop and looking at every digit ( in second loop ) to add.
And /n at the end of elements make the .isDigit() function disabled to find the digits.
So your updated code should be like this :
f = open('file6.txt', 'r') suma = 0 file = f.readlines() for line in file: if line.strip().isdigit(): suma += int(line) print("The sum is ", suma)
Hope it helps!
Answered By – sachin