The string conversion throws me off. I’m only doing it because the hint suggested it’s one possible path to the solution, but now I’m entrenched in doing it that way and I feel like–as Ionatan said–I’m just guessing.
sum_n the object of my code? Everything before that is building up to that line of code. The way I understand it, what I need to do is take an integer,
n, (let’s use the example of 1,234) iterate through each digit (1, then 2, then 3, then 4) adding them all together. What I’m trying to do is take
x, which ought to be individual digits in
n (e.g. 1, 2, 3, and 4) and put them into a bucket, one at a time. Then at the end, that bucket is the sum of 1+2+3+4.
sum_n is my bucket–the sum of all the digits in
n added up.
So (the way I understand it),
x should be 1 at one moment, then the next moment it should be 2, then 3, then 4. Each of those digits, in sequence, should be piled into
sum_n so that the value of
sum_n should be 1, one moment, then 3 [1+2], then 7 [1+2+3], then 10 [1+2+3+4]. That isn’t happening with my code, though, for some reason. I can’t see any reason why it shouldn’t be, but it’s not.
I actually forgot that updating a variable,
x += 1 is the same as saying
x = x + 1.
I erased everything I had and started from scratch, but it looks like I came up with the exact same thing, only now I have the word “return” in there:
def digit_sum(n): str_n = str(n) sum_n = 0 for x in str_n: int_x = int(x) sum_n += int_x return sum_n
The little error at the bottom:
Your function fails on digit_sum(434). It returns 4 when it should return 11.