Why is this code not working to sum the values in s?? | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 2

Why is this code not working to sum the values in s??

s='1.23 , 2.34 , 3.123' ans=0 for i in s: ans = ans + int(i) print (ans) Why is it bringing value error??

29th Jul 2020, 2:43 PM
Adeola Adetilewa
Adeola Adetilewa - avatar
3 Antworten
+ 8
an other pythonic way to do the summation could be: it's better to use a list instead of a string: s=[1.23 , 2.34 , 3.123] print(sum(s)) # if input can not be other than this, split and sum: s='1.23 , 2.34 , 3.123'.split(',') print(sum([float(i)for i in s]))
29th Jul 2020, 3:14 PM
Lothar
Lothar - avatar
+ 3
because s is a string and when you search a string with a for loop, you look at each induvidual character. '.' is not a number, so int('.') raises a value error try: s=[1.23,2.34,3.123]
29th Jul 2020, 2:46 PM
Slick
Slick - avatar
+ 1
Thanks y'all really appreciate 😊
29th Jul 2020, 3:17 PM
Adeola Adetilewa
Adeola Adetilewa - avatar