4/15 concept of how the code works


#1

Hey everyone. I don't understand at all how this code works, I found it here on the forum and it actually works.

def digit_sum(n):
    ln=str(n)
    summ = 0
    for l in ln:
        num = int(l)
        summ += num
    print summ
    return summ

So, what I don't understand is when the computer separates the integer you have and it makes the summ with each integer, how does it know the computer to separate them and then make the summ without having a "variable" ? Anyway I would like an explanation of how the code works.

Thanks in advance.


#2

Hi, @zeby11!
Your code works this way:
Your function digit_sum will get a value, as an argument, and such will be stored in your variable "n".
Right after your function definition, you'll tell the compiler to get that value stored in n and convert it into a string.

Note: you can check by doing print type(n).

After that, you'll use a loop instruction, in this case for, to iterate over your string.
Like it was presented to you in earlier lessons, you'll iterate through each character of your string. The variable you'll use to iterate over that string, "l", will hold each character per loop executed.

Inside of your loop, you'll convert that exact same value into an integer and store that into the variable called num.

After that, you'll get that value stored in num and store in summ.

After all of this, you'll print summ and return that value so the execution of your program will return to where the function was called.

Hope I was clear, if not, let me know and I'll explain in a different way :slightly_smiling:

Edit:

#This is how your loop works!
#Value stored in stringVariable is "zeby101"
for character in stringVariable:
    print character

1st iteration: character will hold the value "z" and will print such value!
2nd iteration: character will no longer hold the value "z", since the loop executed again and since it didn't reach the end of the string, but now it will hold the value "e".
And so on until it reaches the end of your string!