4. digit_sum


#1



https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/0/4?curriculum_id=4f89dab3d788890003000096#


Oops, try again. Does your digit_sum function take exactly one argument (a positive integer)? Your code threw a "'int' object is not iterable" error.


I have no idea what is wrong. Please help.


 
def digit_sum(n):
    n = int(n)
    for num in n:
        total = 0
        total += num
    return total


#2

here:

for num in n:

n contains an integer, you can't loop over integers


#3

would it be 'for n' then?


#4

what you are trying to do is loop over an integer, that doesn't work

maybe you can convert the integers to string? strings are iterable


#5

Good advice from @stetim94 :smile:

It is a good idea to be familiar with Python Built-in Functions. They often come in handy.


#6

thanks I am checking it out now :slight_smile:


#7

sorry but i am extremely stuck. i always struggle with python


#8

yea, like str, very useful


#9

One of the Python built-in functions is perfect for doing that. Hint: The type of a Python string object is str.

Also read about int.


#10

def digit_sum(n):
n= str(n)
total = 0
total += n
return total
i tried to do it. sorry you're helpful but i struggle a lot


#11

now n is a string, you can loop over it.


#12

Oops, try again. Does your digit_sum function take exactly one argument (a positive integer)? Your code threw a "unsupported operand type(s) for +=: 'int' and 'str'" error.

it says this for:
def digit_sum(n):
n = str(n)
for num in n:
total = 0
total += num
return total


#13

you should declare total outside the loop, otherwise what you add to total won't persist

now num is a string, so you need to cast it to integer again before adding it total


#14

def digit_sum(n):
n = str(n)
total = 0
for num in n:
num = int(num)
total += num
return total
THANKS SO MUCH!!!!! :smile:


#15

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