Check Harshad Number in Python
Divide 18 by its digit sum to check a Python Harshad number. Beginner steps explain generators, positive-input rules, and short-circuit protection from zero.
1# Program to check Harshad (Niven) number23num = int(input("Enter an integer: "))45digit_sum = sum(int(d) for d in str(abs(num)))67if num > 0 and 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
18 is a Harshad number
18 divided by its digit sum 9 leaves remainder zero.
In this one
- Sum digits with a generator
- Short-circuit a zero-divisor check
- Enforce a positive-number definition
How it works
- 1
Read num and sum the digits of its absolute value.
- 2
Require positive num and a nonzero digit_sum before the modulus.
- 3
Test num % digit_sum == 0 and print the result.
Edge cases
Zero
Enter 0.
The digit sum is zero, so the guard skips modulo and reports not Harshad.
Negative input
Enter -18.
Digits can be summed safely, but the positive-number requirement rejects it.
What's going on
A Harshad number is a positive integer divisible by the sum of its decimal digits. For 18, the digit sum is 1 + 8 = 9, and 18 % 9 is zero.
The generator converts each character in str(abs(num)) to an integer, and sum adds the digits. abs keeps a minus sign out of digit conversion. The and condition checks digit_sum != 0 before taking a remainder, so zero cannot cause division by zero.
The final condition also requires num > 0 because the definition used here is for positive integers. Without that restriction, negative multiples would pass the divisibility calculation too. The program is checking a digit property, not asking whether a number is prime or perfect.
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.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why check digit_sum before modulo?
Pick an answer to check it.
Question 2
Why does 18 pass?
Pick an answer to check it.
Questions people ask
Why check digit_sum before modulo?
A zero divisor would raise ZeroDivisionError, and short-circuiting avoids it.
Why does 18 pass?
Its digit sum is 9 and 18 is divisible by 9.
Why apply abs before converting digits?
It removes a negative sign from the text so int only receives digit characters.