In this simple python program, we have to display happy numbers in between a range. It's a beginner-level python program.
To understand this example, you should have knowledge of the following Python programming topics:
In this beginner python program example, We already discuss the happy number in our previous program. Please refer to the python program to check a number is a happy number for more details. Just an introduction to what is a happy number is A number in which the sum of the square of its digits which we were doing it continuously for every result till we get a resultant 1. else it's not a happy number.
In this basic python program, we need to print the happy numbers between 1 and 100. So we need to check every number between 1 and 100 as a happy number or not using if condition
in python. If that is a happy number, we print that number else; we move to the next number.
In this simple python program, we use a for loop
starting from 1 to 100 using the range method in python programming language and then store that number to a variable and for each number in that loop, open a while loop
till the result from the user-defined function is not equal to 1 or 4, inside that while loop
we call the function to calculate the sum. And we check if the returned value from the function is one or not. If it is a 1, then print
that number, because it is a Happy number.
STEP 1: Print a message as the happy numbers are using print statements in python language.
STEP 2: Open a for loop
from 1 to 100 using the range method to check every number for a happy number or not.
STEP 3: Assign or copy the number to a variable.
STEP 4: Open a while loop
till the return value from the user-defined function is not equal to 1 and 4.
STEP 5: Call the function to calculate the sum of the square of the number until we get a resultant.
STEP 6: Check the result is equal to zero using an if
condition in python language. Then if so, print
that number else iterate the next number using for loop
. we use a space character in between every happy number in printing
STEP 1: Define the function and get the parameters from the main program.
STEP 2: Initialize two variables for sum and remainder as zero
STEP 3: Open a while loop
until the number is greater than zero.
STEP 4: Get the remainder of the number using a mod operator and add the sum as sum + square of the remainder.
STEP 5: Divide the number by 10 to split the number and get the next digit.
STEP 6: Return the sum to the main program using python syntax.
def hnum(num):
rem = sum = 0
while(num > 0):
rem = num
sum = sum + (rem*rem)
num = num//10
return sum
print("Happy numbers between range 1 and 100 are: ")
for i in range(1, 101):
result = i
while(result != 1 and result != 4):
result = hnum(result)
if(result == 1):
print(i)
Happy numbers between range 1 and 100 are 1 7 10 13 19 23 28 31 32 44 49 68 70 79 82 86 91 94 97 100