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

5
Contributors
5
Replies
9
Views
8 Years
Discussion Span
Last Post by willygstyle

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:

print( sum_digit_squares(123) )

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

Edited by vegaseat: renamed function properly

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

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

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``````

Edited by willygstyle: forgot code hahaha

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.