0

My code:

def digit_sum(n):
    result = 0
    s = str(n)
    for c in s:
        result += (int)c    # invalid syntax??????????
    return result

print digit_sum(1234)

Result:

    result += (int)c    # invalid syntax??????????
                   ^
SyntaxError: invalid syntax

The function is supposed to return the sum of each digit of the argument "n". Why do I get SyntaxError in the commented line? The variable c is of type string so it shouldn´t be an issue to apply a type cast to int.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
Marcel
  • 21
  • 1
  • 3

3 Answers3

7

In Python you do not cast that way. You use:

result += int(c)

Technically speaking this is not casting: you call the int(..) builtin function which takes as input the string and produces its equivalent as int. You do not cast in Python since it is a dynamically typed language.

Note that it is of course possible that c contains text that is not an integer. Like 'the number fifteen whohaa'. Of course int(..) cannot make sense out of that. In that case it will raise a ValueError. You can use try-except to handle these:

try:
    result += int(c)
except ValueError:
    # ... (do something to handle the error)
    pass
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
2

In Python, you cast a string to an integer by using a function int().

    result += int(c)
Rok Povsic
  • 4,626
  • 5
  • 37
  • 53
0
def digit_sum(n):
        numsum=[]
        add_up=str(n)
    for n in add_up[0: len(add_up)]:
        numsum.append(int(n))
    return sum(numsum)
print digit_sum(1234)

Basically, you need to cast string to integer using int(n)

Umang Gupta
  • 15,022
  • 6
  • 48
  • 66
Melansia
  • 1
  • 1
  • 2