Digit_sum


#1

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

<Below this line, add a link to the EXACT exercise that you are stuck at.>

<In what way does your code behave incorrectly? Include ALL error messages.>

<What do you expect to happen instead?>
Hello, I have a big problem in the problem digit_sum! I could understand what the question ask and what it wants me to do but I thought I better to change the number into a string and then using spliting the numbers, adding them together! but First: As I tried I couldnt do that practise ! second : I got help by getting code and even I got more confused now!
Plz Give me any kinda help do you think may help me
Thank you in advance

```python

Replace this line with your code.

<do not remove the three backticks above>

#2

that is good, but then the tricky bit is to actually build a program around it

I think your thought process is good, but i would need to see the code to correct where it goes wrong


#3

Dear Kind stetim94,
Thank you so much for your kind reply.
I thought maybe I better to make a list of the number in string
then I tried to make them into int,
so right now I have int numbers and must add them together!
I tried to apply by method sum which did not work!
My code do nothing for having a sum which is my problem and dunno how to do that
n = 1234
lista = []
for number in str(n):
lista.append(number)

for number in lista:
total = 0
total += int(number)
print(total)


#4

the list step is not needed, we can simply iterate over a string version of n and add them directly to total, so then you get:

for number in str(n):
     total += int(number)

first to a list, and then looping over the list is a bit double

well, we need to declare total outside the loop, otherwise total gets re-assigned a value of zero each iterations of the loop, which is slightly problematic


#5

Awwwww It works!!! Thank you soooo much.
You know I think as a beginner one, sometimes I forget that some simple ways are better that making a code complicated!
Now That you told me the way, I found it.
Thank you very much <3


#6

you understand why placing total = 0 outside the loop is so critical? Otherwise, the values we add to it won’t stick, given we just re-assign zero each iteration of the loop

Of course you can have the list, but its not necessary

simple is usually preferred over complicated.


#7

when I just the total inside the loop, at the end, it will shows me the last number of x.


#8

yea, each iterations of the loop then assign 0 to total, so only the last value stacks given no more iterations are done


#9

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