Quick actions

cmd+k|ctrl+k

Navigation

Languages

SumofDigits

Snippet info

Language

Python

Visibility

public

Author

masterhun

Created

2024-01-01T18:47:10.070005Z

Updated

2024-01-01T18:52:45.6912Z



# Sample Python code 
# Python 3 program to
# compute sum of digits in
# number.
# Function to get sum of digits
def getSum(n):
    sum = 0
    while (n != 0):
        sum = sum + (n % 10)            # This mod operation gets us the right most digit.
        print( "digit: " + str(n % 10) )
        print( "sum: " + str(sum) )
        n = n//10                       # This floor division (n//10) chops off the right most digit. 
        print( "n: " + str(n) )         # n = n//10 can also be coded as n = int(n/10)
        print()
    return sum                          
    
n = 12345

print( "n: " + str(n) )

print()

print( "The sum of the digits of " + str(n) + " is " + str(getSum(n)) + "." )
# Output: 15 = 1 + 2 + 3 + 4 + 5 
INFO