Онлайн компилятор Python

n = int(input("Enter a non-negative integer: ")) total = 0 while n > 0: total += n % 10 n //= 10 print(f"Sum of digits: {total}")
This code calculates the sum of the digits of a non-negative integer. It repeatedly extracts the last digit using the modulo operator and removes it with integer division, adding each digit to a running total.

- The loop condition `n > 0` means the loop stops when `n` becomes 0. What happens if the user enters `0`? The loop never runs, so `total` stays 0, which is correct for the sum of digits of 0. However, think about what happens if the user enters a negative number — the loop won't run either, but the problem says "non-negative", so that's fine.

- Consider what happens with a number like `100`. The loop runs three times: first adds 0, then 0, then 1. The total becomes 1, which is correct. But trace through the code for `n = 100` step by step to see if the order of operations (adding before dividing) matters.