My code doesn't work for more then 2 digits numbers and and negative numbers

Issue

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)

file6.txt:

1
10

Output:

The sum is  2

Solution

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

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published