π Day 36/150 – Sum of Digits of a Number in Python
The sum of digits means adding all digits of a number.
Examples:
1234 → 1 + 2 + 3 + 4 = 10
507 → 5 + 0 + 7 = 12
Let’s explore different ways to find sum of digits in Python π
πΉ Method 1 – Using while Loop
n = 1234
total = 0
while n > 0:
digit = n % 10
total += digit
n //= 10
print("Sum of digits:", total)
✅ Best method for logic building.
πΉ Method 2 – Taking User Input
n = int(input("Enter a number: ")) total = 0 temp = abs(n) while temp > 0: total += temp % 10 temp //= 10 print("Sum of digits:", total)
✅ Works for negative numbers too.
πΉ Method 3 – Using String + sum()
n = 1234
total = sum(int(i) for i in str(abs(n)))
print("Sum of digits:", total)
✅ Shortest and cleanest method.
πΉ Method 4 – Using Recursion
def digit_sum(n):
n = abs(n)
if n == 0:
return 0
return n % 10 + digit_sum(n // 10)
print(digit_sum(1234))
✅ Great for recursion practice.π― Output
Sum of digits: 10
π Key Takeaways
- Use % 10 to get the last digit.
- Use // 10 to remove the last digit.
- sum(int(i) for i in str(n)) is easiest.
- Use abs(n) for negative numbers.


0 Comments:
Post a Comment