# 4. digit_sum

#1

hi everyone, im having (i guess) some concept issues appearing in this excercise, the code is:

1. if i replace the return lista for print lista, the code works ok, instead if i leave the return, the code dont work. (i have no idea why xD)
2. in a for loop, what if i want to return the value AND also print it in console?

``````def digit_sum(n):
suma=0
lista=[]
n_str=str(n)
for i in n_str:
lista.append(i)
return lista  #this is the problem print instead of return works well, i dont know why that logic

for i in lista:
suma+=int(i)
return suma
print suma  #can i do something like this?

digit_sum(24)``````

#2

@netace54312,
One of the qualities of the return statement is that it will cause an =immediate EXIT= of the function.
It also return's a result with NO-Display

Now as you want both the lista and the suma to be =returned=
you have to think about a mechanism to keep track of those Value's
You could for instance use

``````def digit_sum(n):
#create an EMPTY dictionary
dummy_dict = {};
dummy_dict["argument"] = n;
suma=0;
lista=[];
n_str=str(n);
for i in n_str:
lista.append(i);
print lista;

for i in lista:
suma+=int(i);
print suma;
#prepare return
dummy_dict["lista"] = lista;
dummy_dict["suma"] = suma;
return dummy_dict;``````

``````#capture the =return= Value in a VARIABLE
result = digit_sum(24);
print result;
print result["argument"]
print result["lista"]
print result["suma"]
#you could create the =string= inside of function & return =string=
print("Digit sum of {0} via list {1} is {2}".format(
result["argument"],result["lista"],result["suma"]));``````

#3

Since your return is not conditional, all the code that follows will never we seen.

Given that you are not mutating the string you made from `n`, we can simply iterate over the string and add each value.to an accumulator variable. No need for a list.

``````    suma = 0
for i in n_str:
suma += i
return suma

print digit_sum(1234)    # 10``````