๐ 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
✅ 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()
✅ Shortest and cleanest method.
๐น Method 4 – Using Recursion
✅ 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.

.png)
.png)
