Given a number and the task is to find sum of digits of this number in Python.
Input : n = 87
Output : 15
Input : n = 111
Output : 3
Below are the methods to sum of the digits.
Method-1: Using str() and int() methods.: The str() method is used to convert the number to string. The int() method is used to convert the string digit to an integer.
Convert the number to string and iterate over each digit in the string and after conerting each digit to integer and add to the sum of the digits in each iteration.
Method-2: Using sum() methods.: The sum() method is used to sum of numbers in the list.
Convert the number to string using str() and strip the string and convert to list of number using strip() and map() method resp. Then find the sum using the sum() method.
Method-3: Using General Approach:
- Get the number
- Declare a variable to store the sum and set it to 0
- Repeat the next two steps till the number is not 0
- Get the rightmost digit of the number with help of remainder ‘%’ operator by dividing it with 10 and add it to sum.
- Divide the number by 10 with help of ‘//’ operator
- Print or return the sum
A. Iterative Approach:
B. Recursive Approach:
- Python Program for Check if all digits of a number divide it
- Python Program to create an OTP by squaring and concatenating the odd digits of a number
- Python Program to check whether it is possible to make a divisible by 3 number using all digits in an array
- Python Program for Difference between sums of odd and even digits
- Python | Sum of number digits in List
- Python Program for Efficient program to print all prime factors of a given number
- Python Program to Find the Number Occurring Odd Number of Times
- Python Program for How to check if a given number is Fibonacci number?
- Python Program for factorial of a number
- Python Program for n-th Fibonacci number
- Python Program for nth Catalan Number
- Python Program for Find sum of even factors of a number
- Python Program for Find sum of odd factors of a number
- Python Program to check Armstrong Number
- Python program to check whether a number is Prime or not
- Python Program for Triangular Matchstick Number
- Python Program to Check Prime Number
- Python program to find number of likes and dislikes
- Python Program for Smallest K digit number divisible by X
- Python Program for Number of elements with odd factors in given range
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.