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?


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:


def digit_sum(n):
    for n>0:
    return s


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:


For more info, read this:


Thnx a lot!!!! it worked


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 :slight_smile:

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


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