Home > other >  I need to find the sum of odd numbers in a file
I need to find the sum of odd numbers in a file

Time:09-28

I need to find the sum and count of odd numbers in a file using python but I'm getting an error like this

if i % 2 == 0: TypeError: not all arguments converted during string formatting

file = open("numbers.txt", "r")
file_contents = file.readlines()

for i in file_contents:
    i = i.strip('\n')
    print(i)
    if i % 2 == 0:
        odd_sum  = int(i)
        odd_count  = 1
    print(odd_sum)

CodePudding user response:

i is a string so you cant calculate a modulo. Try to do your casting to int() in line 5:

i = int(i.strip('\n'))

instead of line 8

odd_sum  = int(i)

If you want to calculate the sum of all odd numbers you can also do:

odd_sum = sum(ii for i in file_contents if (ii := int(i.strip('\n'))) % 2 == 1)

CodePudding user response:

Just cast the 'i' in this line to int:

 if int(i) % 2 == 0:
  • Related