0

I'm trying to calculate the sum of multiple numbers in one list, but there always appears an error. These numbers are readed from a txt.

Numbers:

19.18,29.15,78.75,212.10

My code:

infile = open("January.txt","r")
list = infile.readline().split(",")
withdrawal= sum(list)

Error:

withdrawal= sum(list)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
2
  • 3
    You are not converting your numbers from the string in text to a numerical format, e.g. float or integers. Have a look at what is inside your variable list, you will see the type will not be integers or floats. Commented Jul 15, 2020 at 11:45
  • 1
    Please be sure that your numbers in the list are all integers Commented Jul 15, 2020 at 11:46

2 Answers 2

2

You would need to convert each element from str to float, you can do this with a generator expression.

with open("January.txt","r") as infile:
    data = infile.readline().split(",")
    withdrawal = sum(float(i) for i in data)
Sign up to request clarification or add additional context in comments.

1 Comment

I am a python beginner, thank you for your answer, which is very helpful to me!
1

The elements of the list are in str format. When they are converted into int or float format, then the sum function will return the sum of the list.

This can be done using the map function as following:

liss=map(float,lis)

Hence :

f=open("January.txt", "r")
lis = f.readline().split(",")
liss=map(float,lis)
withdrawal= sum(liss)
print(withdrawal)

This will produce the desired output.

Hope this was helpful!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.