I'm a newbie to python. I'm going through the wonderful 'how to think like a computer scientist tutorial' and I've come up with a question that I'm not sure how to get it to add the results at the end. Here's the question and my working so far :)

def sum_of_squares_of_digits(n):
    >>> sum_of_squares_of_digits(1)
    >>> sum_of_squares_of_digits(9)
    >>> sum_of_squares_of_digits(11)
    >>> sum_of_squares_of_digits(121)
    >>> sum_of_squares_of_digits(987)
    sum = []
    squares = []
    num = []
    index = 0
    while n:
       num = n % 10
       squares = num*num
       n = n / 10
    sum += squares
    print sum

This would give you the sum of digits:

def sum_digits(n):
    total = 0
    for digit in str(n):
        total += int(digit)
    return total

Now expand this function so you multiply int(digit) with each other.
Notice that I didn't use 'sum' because sum() is a Python function.

while n:
       num = n % 10
       squares = num*num
       n = n / 10

"while n:" evaluates to True/False. If n==0, then it is False, otherwise True (for both positive and negative numbers). So you would have an infinite loop, except for the fact that that you are using integers, so a some point n will equal one and the next pass will round to zero using integers. Anyway, this is not a good way to do this as you missed an infinite loop by luck only, and hopefully you now understand while loops a little better.

Thanks so much sneekula and woooee. I guess I was trying to use a 'while' loop because in the tutorial 'for' loops was the next lesson. You've definately put me on the right track. Thanks

For a sequence with a finite length like you have in str(n), the for loop is ideal. Welcome to DaniWeb! Hope you have fun with Python programming!

This article has been dead for over six months. Start a new discussion instead.