- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions

# Python program to check if the given number is Happy Number

When it is required to check if a given number is a happy number, the ‘%’ operator, the ‘//’ operator and the ‘+’ operator can be used.

A Happy number is the one that ends up as 1, when it is replaced by the sum of square of every digit in the number.

Below is a demonstration for the same −

## Example

def check_happy_num(my_num): remaining = sum_val = 0 while(my_num > 0): remaining = my_num%10 sum_val = sum_val + (remaining*remaining) my_num = my_num//10 return sum_val; my_num = 86 my_result = my_num while(my_result != 1 and my_result != 4): my_result = check_happy_num(my_result); print("The number is being checked") if(my_result == 1): print(str(my_num) + " is a happy number"); elif(my_result == 4): print(str(my_num) + " isn't a happy number");

## Output

The number is being checked 86 is a happy number

## Explanation

- A method named ‘check_happy_num’ is defined, that takes a number as parameter.
- It checks to see if the number is greater than 0.
- A sum variable is assigned to 0.
- It divides the number by 10 and gets the remainder, and assigns it to a value.
- This remainder is multipled with itself and added to a ‘sum’ variable.
- This occurs on all digits of the number.
- This sum is returned as output.
- The number is defined, and a copy of it is made.
- It is checked to see if it is a happy number by calling the function previously defined.
- Relevant message is displayed on the console.

- Related Articles
- Python program to check if the given number is a Disarium Number
- Python program to check if a given string is number Palindrome
- Python Program for How to check if a given number is a Fibonacci number?
- How to check if a given number is a Fibonacci number in Python Program ?
- Java Program to Check if a given Number is Perfect Number
- Swift Program to Check if the given number is Perfect number or not
- Python Program to Check if a Number is a Perfect Number
- Python Program to Check if a Number is a Strong Number
- Check if the given number is Ore number or not in Python
- Java Program for check if a given number is Fibonacci number?
- Check if given number is Emirp Number or not in Python
- Program to check whether given number is Narcissistic number or not in Python
- Happy Number in Python
- Check if given number is perfect square in Python
- Program to check given number is a Fibonacci term in Python

Advertisements