+ 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)
7 ответов
+ 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"))
+ 4
This is my try Adeola Adetilewa https://code.sololearn.com/cIEqpvliNvoe/?ref=app
+ 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
+ 1
Its only returning ['2']
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..?
0
Thanks...it works, my mistake was putting the return inside the if block code...
0
Thanks Jayakrishna🇮🇳 ...😘😘