+ 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??
3 Respostas
+ 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]))
+ 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]
+ 1
Thanks y'all really appreciate 😊