Python BasicsEasy

Sum of digits of a number

Detailed guide and Python implementation for the 'Sum of digits of a number' problem.

Problem Statement

Easy

Write a function sum_of_digits(n) that takes a non-negative integer n and returns the sum of its digits. For example, the digits of 123 are 1, 2, and 3, and their sum is 6.

Constraints
  • 0 <= n <= 10^9

Examples

Example 1
Input
n = 123
Output
6
Explanation

1 + 2 + 3 = 6.

Example 2
Input
n = 9999
Output
36
Explanation

9 + 9 + 9 + 9 = 36.

Example 3
Input
n = 0
Output
0
Explanation

The only digit is 0, so the sum is 0.

Need a Hint?
Consider using Basics-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.