This digit_sum code worked for others in forum, why do i get syntax error?


#1

def digit_sum(n):
    string = list (str(n))
    print string
	summa = 0
	for c in string:
		calc = int(c)
		print c
		summa += int(c)
	return summa
	
    digit_sum(18)
    digit_sum(99999)

Error:

    File "python", line 4
    summa = 0
   ^
IndentationError: unexpected indent

#2

Hi @pseudosasa

Are you making sure to indent after the for loop then 'un-indent' when you return a value. Its a little hard to tell by the way your code is displayed in the forum.


#3

@pseudosasa Having formatted your code, the error becomes apparent which is that every statement of yours after the line summa = 0 has an extra indent of four spaces. Remove these spaces, and your code should be:

def digit_sum(n):
    string = list (str(n))
    print string
    summa = 0
    for c in string:
	calc = int(c)
	print c
	summa += int(c)
    return summa
	
digit_sum(18)
digit_sum(99999)

which resolves the error :slightly_smiling:


#4

thanks, pls see my next reply to Summa G


#5

OK, thanks and sorry in advance. this is the first time i have ever posted code in a forum, so i am ignorant in numerous ways. First, I'm not sure how to paste in a way to preserve my formatting. I tried ''' around the block, but not sure if that works. Is there an easy tried and true way. or, is grabbing an image and posting it the best way?
Secondly, my entered code looked identical to yours', but it still generated the error. I can only imagine some anomaly with hidden characters. What i posted was only 1 of many permutations i created in desperation as i feel asleep. this code generates the same line 4 error


#6

The code does work:

make sure to preserve indentation the way I have it while entering the code in the editor. Let me know if this doesn't help.


#7

thanks, and sorry if my reply wasn't clear. I agree your code works, i pasted it and saw that it works myself. The issue that I do not understand is this: I also typed in code that looked identical to your code, but it didn;t work. It is related to formatting or some hidden character . For now, I will avoid this issue and carry on.

But I would like to repeat my other question - what is the proper was for me to copy and paste my code so that it is clear and readable. I'm not sure how to use the ''' or the tool that was mentioned on the site.


#8

Here's a nice post on how to format your code in these posts to make it clearly visible :slightly_smiling: