Search code examples
pythonpython-3.xlistaverage

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


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

TypeError: not all arguments converted during string formatting

code:

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)

Solution

  • Just cast the i in this line to int:

     if int(i) % 2 == 0: