0

Write a python program that has a user input a string of three numbers separated by commas, such as "32, 13, 15", and prints the sum of the numbers.

For example Enter your three numbers separated by commas: 32, 13, 15 The sum is 60

I am able to print out the string with the split at the comma, but cannot figure out how to do the sum portion.

sushanth
  • 8,114
  • 3
  • 15
  • 27
  • You haven't mentioned in which programming language you want to achieve it. – sushanth May 24 '20 at 04:16
  • Does this answer your question? [Sum a list of numbers in Python](https://stackoverflow.com/questions/4362586/sum-a-list-of-numbers-in-python) – sushanth May 24 '20 at 04:19
  • You can try splitting the string using `, ` as the delimiter to get the individual numbers. Then you can parse each token to gen the actual integers and calculate the sum. – prashantpiyush May 24 '20 at 04:21
  • @AmberBarnes, post what you have tried so far, it help's to identify the problem & provide recommendations. – sushanth May 24 '20 at 04:25
  • Does this answer your question? [How to sum a list in python](https://stackoverflow.com/questions/39282624/how-to-sum-a-list-in-python) – RoadRunner May 24 '20 at 04:38

2 Answers2

1

You can split the string by commas to get the numbers, convert them from string to int, and add these up using the build-in sum function:

txt = '32, 13, 15'
ans = sum([int(i) for i in txt.split(',')])
print(ans)
MrBean Bremen
  • 12,145
  • 3
  • 19
  • 36
yashtodi94
  • 510
  • 5
  • 9
0
txt = '32, 13, 15'
list_numbers = txt.split(',')
sum = 0
for num in list_numbers:
    sum += int(num)
print(sum)

output: 60

pyOliv
  • 1,118
  • 5
  • 20
  • 2
    why not use inbuilt ```sum``` function ? – sushanth May 24 '20 at 04:26
  • 1
    @Sushanth `print(sum([int(i) for i in txt.split(',')]))` is indeed a one line of pythonic code, but I guess it is more complicated to understand at first glance. It is just my opinion. – pyOliv May 24 '20 at 04:42