# Digit_sum

#1

This is my code

Can some one tell me why cant I use this logic?

The error shown is:

File "python", line 3
for n>0:
^
SyntaxError: invalid syntax

Why is it an invalid syntax?

#2

Please post the code manually. The link takes us to the course, showing us the code that we wrote.
Refer to this for posting code:

#3

``````s=0
def digit_sum(n):
for n>0:
d=n%10
s=s+d
n=n/10
return s
digit_sum(124)``````

#4

`while` and `for` loops are similar, but not the same, especially when it comes to syntax.
`while` loops:

``````while <condition>:
# Do something``````

`for` loops:

``````for <iterator> in <iterable>:
# Do something``````

`while` loops are essentially `if`-s which keep repeating, i.e., they check for a `<condition>`, and `while` that is `True`, they keep `# Doing something`
`for` loop go over an 'iterator' (lists, dictionaries, tuples, etc.).

For example, the following two loops are the same, but syntactically different:
`while` loop:

``````i = 0
while i <= 5:
print i
i += 1``````

`for` loop

``````for i in range(6):  # Equivalent to for i in range(0, 6):
print i``````

Output for both:

``````1
2
3
4
5``````

#5

Thnx a lot!!!! it worked

#6

I do not know how to do for this one. If someone can give me any comments on my code and how to avoid the "list1" presence, it will be very appreciated

list1 = [213]

def digit_sum(n):
sum_list = 0
list1 = [213]

``````for n in range(len(list1)):
return str(n)
for n in list1:
sum_list = sum_list + int(n)
return sum_list

return digit_sum``````

#7

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