I'm working on an assignment in Python and don't understand the problem with my code.
Based on other answers on Stack Overflow, the answer seems to be:
def digit_sum(number):
return (sum(int(digit) for digit in str(number)))
Where as my code (below) is not working. Why not?
def digit_sum(number):
for digit in str(number):
return sum(int(digit))
You broke the for loop with a return
before the loop finishes. You need to store the accumulative sum and then return it after the loop finishes.
Also, you need to understand what is a 'Single line for loop' in Python. Let's see what does the return
mean in your first block of code:
(sum(int(digit) for digit in str(number)))
We can turn this line into multiple steps:
This step can be done like this
def get_digits_as_string(num):
return [digit for digit in str(num)]
Running above function you can see
>>> get_digits_as_string(12345)
['1', '2', '3', '4', '5']
We just type cast single string
element in the array into int
def get_digits_as_int(num):
return [int(digit) for digit in str(num)]
if you run it you will get:
>>> get_digits_as_int(12345)
[1, 2, 3, 4, 5]
int
This is equivalent to your first block of code
def digit_sum(num):
return sum([int(digit) for digit in str(num)])
Here is a post that is helpful if you want to know more about Single Line for Loops: https://blog.teamtreehouse.com/python-single-line-loops
Hope my answer helps.
Your code doesn't work because you are returning too early.
The return keyword takes whatever you give it and returns it to the caller of the function.
In the first iteration of the for loop, you calculating the sum of the first digit and then returning it.
EG: Number is 1234
so the for loop is iterating over "1234"
So the first digit of "1234" is "1"
Then you take the sum of 1 (whatever that means lol)
And so you would return the number 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.