Editor

Reverse and Add

Advanced · Stretch · from Python While Loops: When For Loops Aren't Enough

From the lesson: Python While Loops: When For Loops Aren't Enough

A vending machine doesn't know how many coins you'll insert. It just keeps waiting: "while the total is less than the price, keep accepting coins." It can't use a for loop because it doesn't know the number of iterations in advance. It needs a while loop.

Read the lesson

Take a number, add it to its own reverse, and repeat until the result reads the same forwards and backwards (a palindrome):

87 + 78 = 165
165 + 561 = 726
726 + 627 = 1353
1353 + 3531 = 4884   (a palindrome after 4 additions)

Write a function steps_to_palindrome(n) that returns how many additions it takes. A number that is already a palindrome needs 0. Some numbers never seem to get there, so give up after 30 additions and return -1.

steps_to_palindrome(87)    # 4
steps_to_palindrome(56)    # 1   (56 + 65 = 121)

Return the answer instead of printing it: Check calls steps_to_palindrome() with its own numbers, some of them hidden.

def steps_to_palindrome(n):
pass
Solution unlocks after your first Check

What Check runs

Your code runs first, then each of these lines, and 5 more that stay hidden. The output must match exactly.

RunsExpected output
steps_to_palindrome(87)4
steps_to_palindrome(56)1

More While Loop exercises

All Python exercises · 50 practice problems · Control Flow quiz