Check Harshad Number in Python

Check whether a number is a Harshad (Niven) number (divisible by sum of its digits).

BeginnerConditional ProgramsExample 12 of 20
check-harshad-number.py
1# Program to check Harshad (Niven) number
2
3num = int(input("Enter an integer: "))
4
5digit_sum = sum(int(d) for d in str(num))
6
7if digit_sum != 0 and num % digit_sum == 0:
8 print(num, "is a Harshad number")
9else:
10 print(num, "is not a Harshad number")

Output

Enter an integer: 18
18 is a Harshad number

What's going on

A Harshad number is divisible by the sum of its digits.

We compute digit sum using a comprehension and check divisibility with modulo.

After this program

If the idea is still fuzzy, read Day 8: Conditional Statements in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 20 conditional programs, or see every topic on Python exercises.