+ 1

Why is my code not working😫😫😫

Assume s is a string,returns the sum of the decimal digits in s. E.g if s is 'a2b3c' returns 5. Def sum_digits(s): For i in s.split(): Result= list(i) For char in result: If char.isdigit(): Lst=list(char) Return sum(list)

17th Sep 2020, 10:04 PM
Adeola Adetilewa
Adeola Adetilewa - avatar
7 odpowiedzi
+ 2
Yes it only returns ["2"] because you wrote return in if block, if char.isdigit() is then it return char as list. You shloud write out of for loop.. Corrected code : def sum_digits(s): sm = 0 for i in s.split(): result= list(i) for char in result: if char.isdigit(): sm+=int(char) return sm #return is out of loop now print(sum_digits("a2b3c")) And also you don't need 2nd loop, it just manking code redundant, after removing makes it less code like this.. : check out difference with your code for what n where need changes : def sum_digits(s): sm = 0 for i in s: if i.isdigit(): sm+=int(i) return sm print(sum_digits("a2b3c"))
17th Sep 2020, 10:57 PM
Jayakrishna 🇮🇳
17th Sep 2020, 10:33 PM
HBhZ_C
HBhZ_C - avatar
+ 3
No need to split the string s.Just create a variable to store the sum of the digits in s and set condition: for i in s: if i isdigit: sum += i return sum
17th Sep 2020, 10:18 PM
HBhZ_C
HBhZ_C - avatar
+ 1
Its only returning ['2']
17th Sep 2020, 10:24 PM
Adeola Adetilewa
Adeola Adetilewa - avatar
0
Is this your total code? Where are calling that defined function...? You need to call that function to work like sum_digits("a2b3c") And copy into playground and paste link here.. Is there Capital letters because of auto caps or using in code? Every small mistake cause error..?
17th Sep 2020, 10:10 PM
Jayakrishna 🇮🇳
0
Thanks...it works, my mistake was putting the return inside the if block code...
17th Sep 2020, 11:06 PM
Adeola Adetilewa
Adeola Adetilewa - avatar
0
Thanks Jayakrishna🇮🇳 ...😘😘
17th Sep 2020, 11:10 PM
Adeola Adetilewa
Adeola Adetilewa - avatar