Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Write a function to find sum of digits of a number
- def digit_sum(n):
- temp = n # store n into temp variable
- sums = 0
- while temp!=0:
- rem = temp%10 # get last digit of temp
- sums += rem # add it to sums variable
- temp = temp//10 # modify temp at the last step
- return sums
- print digit_sum(1234)
- =================================================================================
- # Program to find sum of digits of a given number using loop (without a function)
- num = 1234
- num = list(str(num)) # Convert int to list type (string first because int is not iterable)
- res = 0
- for digit in num:
- res += int(digit) # Convert back to int so that can do addition
- print(res)
Add Comment
Please, Sign In to add comment