Python bootcamp · Lab 26

Sum of digits

easyWhile Loops10 minLesson: While Loops

Read the question, write Python on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read a non-negative integer and print the sum of its digits.

Peeling off n % 10 and then n //= 10 is the classic loop for this.

Input. One line: an integer n ≥ 0.

Output. One integer: the digit sum.

Constraints

  • 0 ≤ n ≤ 1,000,000,000

Examples

Example 1 — 1+2+3.
Input
123
Output
6
Example 2
Input
0
Output
0
Hint
  1. You can also sum(int(d) for d in str(n)).
  2. A while loop: total += n % 10; n //= 10.
Show correct code

Peek only after you have tried. You can still Check your own version.

n = int(input())
print(sum(int(d) for d in str(n)))
main.pyPython · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.