karlakmkj

Practice - sum of digits

Feb 16th, 2021 (edited)
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.70 KB | None | 0 0
  1. # Write a function to find sum of digits of a number
  2. def digit_sum(n):
  3.   temp =# store n into temp variable
  4.   sums = 0
  5.   while temp!=0:
  6.     rem = temp%10   # get last digit of temp
  7.     sums += rem     # add it to sums variable
  8.     temp = temp//10  # modify temp at the last step
  9.   return sums
  10.  
  11. print digit_sum(1234)
  12. =================================================================================
  13. # Program to find sum of digits of a given number using loop (without a function)
  14.  
  15. num = 1234
  16. num = list(str(num)) # Convert int to list type (string first because int is not iterable)
  17. res = 0
  18.  
  19. for digit in num:
  20.     res += int(digit) # Convert back to int so that can do addition
  21. print(res)
Add Comment
Please, Sign In to add comment