Logic Building
# Take number
num = int(input("Enter a number: "))
# Sum of digits
digit_sum = 0
temp = abs(num)
while temp > 0:
digit = temp % 10
digit_sum += digit
temp //= 10
print(f"Sum of digits: {digit_sum}")Output
Enter a number: 1234 Sum of digits: 10
Extract digits and add them.
Key Concepts:
- Extract last digit using modulo
- Add to sum
- Remove last digit using integer division