Search code examples
pythonintsquare

Method to square every digit of an int not working


def square_digits(num):
    x = 0
    for i in str(num):
        y = int(i) * int(i)
        x += y 
    return x

The above code is supoose to square every digit of an integer and concatenate it that is passed in but it doesnt do that. I ran the belpow code and it gives the output 164.

square_digits(9119)


Solution

  • If you want it to output 811181, you need to change x to a string :

    def square_digits(num):
        x = ''
        for i in str(num):
            y = int(i) * int(i)
            x += str(y) 
        return x