# Check If A Number Is A Harshad Number or Not in Python

In this tutorial, we will be looking at a program in Python that will check if a number is a harshad number or not. We will be using the following Python concepts:

- Python if…else Statement
- Functions
- Loops in Python

### Harshad Number

A number is called a harshad number if the number is divisible by the sum of its digits. Harshad numbers are also known as Niven numbers. For example:

156 is divisible by the sum of its digits, i.e. 1 + 5 + 6 = 12

num = int(input("Enter a number: ")) digit = sum = 0 temp = num # Calculates sum of digits while(temp > 0): digit = temp % 10 sum = sum + digit temp = temp // 10 # Checks whether the number is divisible by the sum of digits if num % sum == 0: print(num, "is a Harshad Number!!!") else: print(num, "is not a Harshad Number!!!")

First, we ask the user to input the number using * int(input(“Enter a number: “))*. In our code, the

*prints our message on the console and also reads the input given as a string. But we want the input to be an integer so that we can perform mathematical operations on them. For this reason, we use the*

**input()***function.*

**int()**We then initiate * temp* as the

*we just read. We also initiate both*

**num***and*

**sum***as 0, this also signifies that they are of*

**digit***type.*

**int**Then we start a * while loop *to find the digits of

*using*

**temp***. We then find the sum of each of these digits by adding it to*

**mod(%)***. This loop continues till*

**sum***becomes equals to 0. At this point we exit the loop.*

**temp**Now we use an * if…else statement* to check if

*is divisible by*

**num***or not. If it is then*

**sum***is a harshad number and we print this. If not then we display that*

**num***is not a harshad number.*

**num**### Output

Enter number: 156 156 is a Harshad Number!!! Enter number: 67 67 is not a Harshad Number!!!

So here it is a simple program to check if a number is a Harshad Number or not.

Also read,

## Leave a Reply