Answer to Question #338677 in Python for Elle Joy

Question #338677

Elle Joy Vasquez 1


Create a Python script that will display the SUM of all even and the SUM of all odd numbers in a text file.


TEXT FILE


20


4


15


30


5


OUTPUT


SUM OF EVEN: 54


SUM ODD: 20

1
Expert's answer
2022-05-08T14:32:38-0400


fname=input('Please input file name: ')
if fname.find(".txt")==-1:#if user forgot format
  fname+=".txt"
sumEven=0
sumOdd=0
with open(fname,mode="r+") as f:
  for line in f:
    ln=list(map(int,line.split()))
    for num in ln:
      if num%2:
        sumOdd+=num
      else:
        sumEven+=num
  f.close()
print("Sum of even: "+str(sumEven))
print("Sum of even: "+str(sumOdd))

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS