Python Program to Check the Number is a Happy Number

Write a Python program to check whether the number is happy or not using for loop. If the repeated sum of the square of individual digits in a number is equal to one, it is a Happy Number. For instance, 28 is a Happy number because

22 + 82 = 4 + 64 = 68

62 + 82 = 36 + 64 = 100

12 + 02 + 02 = 1

For more Python programs, please refer to the Python Basic Programs article.

import math

def digitsSquareSum(Number):
    Sum = rem = 0
    while Number > 0:
        rem = Number % 10
        Sum = Sum + math.pow(rem, 2)
        Number = Number // 10
    return Sum


Number = int(input("Enter the Number to Check Happy Number = "))
Temp = Number

while Temp != 1 and Temp != 4:
    Temp = digitsSquareSum(Temp)

if Temp == 1:
    print("\n%d is a Happy Number." %Number)
else:
    print("%d is Not an Unhappy Number." %Number)
Python Program to Check the Number is a Happy Number

This program is a simple solution to find a happy number. Here, we convert the number to a string and use a for loop to iterate over characters. Next, int() converts each character to a digit, and the exponent operator (**) finds the square of a digit. Next, the sum() function adds them. Refer to Python arithmetic operators.

n = int(input("Enter the Value = "))
val = set()

while n != 1 and n not in val:
val.add(n)
n = sum(int(i) ** 2 for i in str(n))

if n == 1:
print("Happy number")
else:
print("It is not a Happy number")
Enter the Value = 22
It is not a Happy number

Enter the Value = 28
Happy number

Also Read