Python List Total

Asked 2 years ago, Updated 2 years ago, 18 views

I'm getting an error trying to get the total of the elements by receiving it as a Python text file list. What should I do?

file = open ("/Users/Jinwoo Baek/Desktop/DSU/Curricular/Programming Introduction/test/test2.txt", "r", encoding='utf-8') s = infile.readlines()

t = sum(s)

print("Total = ",t)

infile.close()

[Error]

t = sum(s)

TypeError: unsupported operand type(s) for +: 'int' and 'str'

python

2022-09-22 15:06

1 Answers

infile=open("/Users/Jinwoo Baek/Desktop/DSU/Curricular/Programming Introduction/test/test2.txt", "r", encoding='utf-8')

s = infile.readlines()

t = 0

for i in s:
    t += float(i)

print ("Total = ", t)

infile.close()

Calling readlines() returns a list of strings If you want to add numbers, you need to convert them into numeric data types.


2022-09-22 15:06

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.