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.

1
  • 1
    In Python you do not cast that way. Commented Feb 25, 2017 at 21:27

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

4 Comments

This can also throw an exception if c can't be converted into an integer. It will throw a ValueErrorexception so if possible treat it with a try-except.
@Gugas: that is indeed a good suggestion. I've added that tho the answer.
sorry but it's an except not a catch to pair with the try.
@Gugas: yeah, some brainfreeze (or being buzzy with too many things at once). Thanks.
2

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

    result += int(c)

Comments

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.