4/15 Help me to understand (warning! working solution!)


#1

Help me to understand why my first solution threw errors but the second - OK (sorry for my English)
First solution - fail (but in my computer it worked)

#!/usr/bin/env python3 
import sys
def digit_sum(n):
    try: 
        int_n = int(n)
    except:
        print ("Error")
        sys.exit()
    if int_n <= 0:
        print ("n must be greater than 0")
    else:
        list_n = list(str(n))
        summa = 0
        for i in list_n:
            summa += int(i)
    return summa
n = input()
print (digit_sum(n))

Second solution - pass

#!/usr/bin/env python3
def digit_sum(n):
    list_n = list(str(n))
    summa = 0
    for i in list_n:
        summa += int(i)
    return summa
n = input()
print (digit_sum(n))

Thank you.


#2

If n is smaller or equal to 0 your code prints "n must be greater than 0", but it doesn't exit the function and tries to return summa, which was never assigned a value.

Oddly enoug it won't let you pass if the function throws an error for n <= 0, but it doesn't matter what you return for those n. It can be some random number or a string or None, as long as there is no error you pass.

Are you aware that codecademy is not using python 3?


#3

Thank you for your answer. I know that Codecademy is not using python3, but I think at a very basic level the difference between 2 and 3 doesn't matter :smile:
Especially since I'm newbie