Sum of Digits

Calculate sum of digits of a number.

IntermediatePhase 2 - Level 2: Number-based Looping LogicExample 4 of 14
sum-of-digits.py
1# Take number
2num = int(input("Enter a number: "))
3
4# Sum of digits
5digit_sum = 0
6temp = abs(num)
7
8while temp > 0:
9 digit = temp % 10
10 digit_sum += digit
11 temp //= 10
12
13print(f"Sum of digits: {digit_sum}")

Output

Enter a number: 1234
Sum of digits: 10

What's going on

Extract digits and add them.

Key Concepts:

Extract last digit using modulo
Add to sum
Remove last digit using integer division