SumofDigits

Run Settings
LanguagePython
Language Version
Run Command
# 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
Editor Settings
Theme
Key bindings
Full width
Lines