How to Find Sum of Digits of a Number in Python
Python's built-in support for lists, strings and data conversion enables us to write very concise code which usually takes much more code in other languages. For example, the following python 3 code computes sum of digits of a number using a generator expression and an implicit iterator.
# python3 code number = int(input("Please enter a number:")) sum_of_digits = sum(int(digit) for digit in str(number)) print("Sum of digits of {} is {}".format(number,sum_of_digits))
The above program illustrates a number of cool features of python language,
- Convert a number to a string using the built-in str() function
- Implicitly convert a string to a sequence of characters to a list when used in looping context
- Use int() built-in function to convert each digit character to a number
- The use of generator expression which return sequence items on demand
- The sum() aggregate built-in function which finally computes the sum of digits
Following is a more traditional way of computing sum of digits of a number in python. Note the use of divmod() function which can compute the remainder and modulus in a single call. The resultant tuple is unpacked into 2 variables.
# python3 code number = int(input("Please enter a number:")) sum_of_digits = 0 n = number while n: n,remainder = divmod(n,10) sum_of_digits += remainder print("Sum of digits of {} is {}".format(number,sum_of_digits))