# Python 15.4:Practice Makes Perfect

#1

Good Morning Friends, I have doubts about a code/solution for:

Can any body please explain how does this code works

The comments are reflect my understanding of code

``````def digit_sum(n):
#Turn the given number sequence into string
a = str(n)
#Create an empty list for holding looped string
b = []
#looping through the string and then appending each element to list"b"
for i in a:
b.append(i)
#????
b = [int(i) for i in b]
c = sum(b)
return c

print digit_sum(56796144687)``````

I am specially confused by this line

``b = [int(i) for i in b]``

#2

It works by changing the i which were appended to b to integers for calculation, since it was previously set to a string.

Your code could also be simplified as:

``````def digit_sum(n):
n = str(n)
total = 0
for c in n:
total += int(c)

print digit_sum(56796144687)``````

#3

Thanks for explanation, I was already thinking along similar lines to your code.

#4

I f you care to look my code for https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/5?curriculum_id=4f89dab3d788890003000096
The following are two different approaches to solution the first one works

``````def factorial(x):
fact=1
for i in range (x):
fact*=i+1
return fact

print factorial(11)``````

The second one doesn't

``````def factorial(x):
if x==1:
return x
else:
return x*(x-1)

print factorial(11)``````

Could you maybe solve challenge without "for" loop

#5

Yes, you could import the functions from math:

``````from math import factorial
def factorial(x):
return math.factorial(x)``````

#6

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