Number Programs: Reverse, Palindrome and Armstrong

50 min read Loops in Depth

This is a free course. Log in to run the code exercises and track your progress.

Number Programs: Reverse, Palindrome and Armstrong

With % 10 (last digit) and // 10 (drop the last digit) a while loop can take a number apart digit by digit. Building the digits back up in the opposite order reverses the number:

n = 1234
rev = 0
while n > 0:
    rev = rev * 10 + n % 10
    n = n // 10
print(rev)    # 4321

A palindrome number reads the same both ways, such as 121 or 4554: it equals its own reverse. Keep a copy of the original number, because the loop changes n.

An Armstrong number equals the sum of its digits each raised to the power of the number of digits. 153 has 3 digits and 1³ + 5³ + 3³ = 1 + 125 + 27 = 153, so it is an Armstrong number. len(str(n)) is a quick way to count the digits.

Python exercise

Read a positive integer and print Palindrome if it reads the same backwards, otherwise Not Palindrome. Reverse it with a while loop (not with strings).

n = int(input())
original = n
rev = 0
# build rev from the digits of n
if rev == original:
    print("Palindrome")
else:
    print("Not Palindrome")

Log in to edit and run this code.