Digit_sum


#1



So, the code is working totally fine in my Python 3. However, on codeacademy I keep getting "Oops, try again. Your function fails on digit_sum(434). It returns None when it should return 11."

Can someone tell me please what is the problem? I really don't understand how it can work fine in Python 3 but not on codeacademy :frowning:


def digit_sum(n):
    n = str(n)
    sumup = 0
    for x in n:
        x = int(x)
        sumup += x
    print (sumup)


#2

To start with, codecademy is based on python 2.

Use return instead of print.

[Using a bracket in print is applicable in python3.]

def digit_sum(n):
    n = str(n)
    sumup = 0
    for x in n:
        x = int(x)
        sumup += x
    return (sumup)
digit_sum(434)

#3

Thanks for the quick reply. I am aware that codeacademy is based on 2 but printing with brackets is totally okay even in Python 2.

It was the "return" instead of "print". Silly me. Thanks a lot!


#4

Sure using a bracket will still work in python2. I thought I should spell things out that way.

In python3, you get to use input() rather than raw_input() as it is in python2, for example to request a user's input.

[Sorry, I edited my previous post after seeing my error myself, too. :grimacing: ]


#5

It's fine :slight_smile: thank you again for your help! I really appreciate it!

Yeah, I noticed that difference as well thus I was really puzzled what I was getting wrong this time.


#6

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