Practice Makes Perfect Python


#1

def digit_sum(n,s):

if(n < 10):
s = n + s
#print s
return s
else:
s = s + n % 10
#print s
digit_sum(n//10,s)

a = digit_sum(1234,0)
print a

why does this code give me None as output


#2

you should state which unit you are doing within the “Practice makes perfect” course so we know what the aim of the exercise is


#3

Your function should take only one parameter, an integer of any size.

def digit_sum(n):

Set your running count to zero at the start of the function.

    total = 0

It looks like you are seeking a mathematical approach with modulo and floor division.

    while n > 0:
        total += n % 10
        n //= 10

After the completion of the loop, return the total.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.