Python Program to Find Sum of Digits Using While Loop
num % 10, adding it to a sum variable, and then removing the last digit with num //= 10 until the number becomes zero.Examples
How to Think About It
num % 10 to get the last digit and add it to a total sum. Then remove that digit by dividing the number by 10 using num //= 10. Repeat this until the number is zero.Algorithm
Code
num = int(input("Enter a number: ")) sum_digits = 0 while num > 0: digit = num % 10 sum_digits += digit num //= 10 print("Sum of digits:", sum_digits)
Dry Run
Let's trace the input 123 through the code
Initial values
num = 123, sum_digits = 0
First iteration
digit = 123 % 10 = 3; sum_digits = 0 + 3 = 3; num = 123 // 10 = 12
Second iteration
digit = 12 % 10 = 2; sum_digits = 3 + 2 = 5; num = 12 // 10 = 1
Third iteration
digit = 1 % 10 = 1; sum_digits = 5 + 1 = 6; num = 1 // 10 = 0
Loop ends
num is now 0, exit loop
| num | digit | sum_digits |
|---|---|---|
| 123 | 3 | 3 |
| 12 | 2 | 5 |
| 1 | 1 | 6 |
Why This Works
Step 1: Extract last digit
Using num % 10 gets the last digit of the number because modulo gives the remainder after division by 10.
Step 2: Add digit to sum
Add the extracted digit to the running total stored in sum_digits.
Step 3: Remove last digit
Use integer division num //= 10 to drop the last digit, moving to the next digit in the next loop.
Alternative Approaches
def sum_digits(n): if n == 0: return 0 return n % 10 + sum_digits(n // 10) num = int(input("Enter a number: ")) print("Sum of digits:", sum_digits(num))
num = input("Enter a number: ") sum_digits = sum(int(d) for d in num) print("Sum of digits:", sum_digits)
Complexity: O(d) time, O(1) space
Time Complexity
The loop runs once for each digit in the number, so time grows linearly with the number of digits, O(d).
Space Complexity
Only a few variables are used regardless of input size, so space complexity is O(1).
Which Approach is Fastest?
The while loop approach is efficient and uses constant space, while recursion uses extra stack space and string conversion may be slower for large inputs.
| Approach | Time | Space | Best For |
|---|---|---|---|
| While loop | O(d) | O(1) | Efficient and memory-friendly |
| Recursion | O(d) | O(d) | Elegant but uses more memory |
| String conversion | O(d) | O(d) | Simple code, good for small inputs |
// to remove digits, not regular division.