Member Avatar for soUPERMan

How do you make a function repeat itself using a while statement.

Here's the function:

# the function accepts any positive integer parameter and returns the sum of
# the squares of its digits.

def zap(intNum):
	total = 0
	while intNum != 0:
		last = intNum % 10
		total += last**2
		intNum = intNum / 10

	return total

You mean a recursive function like this ...

def sum_digit_squares(intNum, total=0):
    """
    return the sum of the squares of intNum digits
    """
    if intNum > 0:
        last = intNum % 10
        x = last**2
        print( last, x )  # for testing only
        # recursive action
        return sum_digit_squares(intNum//10, total+x)
    else:
        return total


print( sum_digit_squares(123) )

"""my result with test print -->
(3, 9)
(2, 4)
(1, 1)
14
"""

Recursive function can replace the while loop, but while loop is more efficient and faster.

Member Avatar for soUPERMan

How do you do it with a while statement??

What i want to do is input a number into the zap function and zap it until the number is either 1 or 4, i've tried using the while statement but i think im doing it wrong because i end up with a non-responsive shell.

Convert the integer to a list or string and iterate over each element/character. You can use a while loop or a for loop.

I had a go at it although its been a "while" since I coded any python so probably ugly. I also didn't change anything but the comment with your function because it seemed more clear to me that, that is what the function does. Also I really liked the way veg did it, but yeah from what I know a while loop is better for memory than a recursive function.

# the function accepts any positive integer parameter and returns the integer squared

def zap(intNum):
	total = 0
	while intNum != 0:
		last = intNum % 10
		total += last**2
		intNum = intNum / 10

	return total

stop = "y"

while stop == "y":
    print "would you like to zap your number?"
    stop = raw_input("y\\n: ")
    if stop == "n":
        break
    x = input("please enter number to zap: ")
    x = zap(x)
    print x
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.