-3

A simple python code for getting sum of every digit in n integer. I tried a while to get the number of digit and for loop to get the sum. Sometime it's working. But sometime it's giving one less. like 22222 should be 10. But i am getting 9.

import math

def number_adder():
    number = int(input('Enter a natural number: ', )) #Inputs user value. Specifically a natural number

    sum = 0

    number_of_digit = 0
    for digit in str(number):
        number_of_digit += 1            # getting number of digit in the input value

    number = number * 10 ** (-number_of_digit + 1)

    sum += math.floor(number)
    number -= math.floor(number)

    for digit in range(number_of_digit - 1):
        number = number * 10
        sum += math.floor(number)

        number -= math.floor(number)

    print('The sum of all digits of the value is, ', sum)


number_adder()
khelwood
  • 55,782
  • 14
  • 81
  • 108
musfiq
  • 1
  • 1
  • 2
    `sum(int(x) for x in str(n))` – dawg Dec 27 '20 at 15:24
  • 1
    And don't use `sum` as a name for a variable. You stomped on the function `sum()` when you did – dawg Dec 27 '20 at 15:25
  • you already iterate over digits `for digit in str(number):` and then you are finding the number of digits which is not needed as you can just do `len(number)` and again if you are iterating of `str(number)` just add `int(digit)` to some variable and that is your answer. – Albin Paul Dec 27 '20 at 15:28
  • 2
    Does this answer your question? [Sum the digits of a number](https://stackoverflow.com/questions/14939953/sum-the-digits-of-a-number) – Tomerikoo Dec 27 '20 at 15:29
  • 1
    But I want to know what is troubling my code. Why is it giving error – musfiq Dec 27 '20 at 16:03

3 Answers3

2

You are making this way too complicated.

Just do:

>>> n=22222
>>> sum(int(x) for x in str(n))
10

And

>>> n=12345
>>> sum(int(x) for x in str(n))
15

Explanation:

sum(int(x) for x in str(n))
                     ^  turn the number into a string
                     ^  strings are iterable character by character  
     ^       ^       ^  a comprehension loop to loop over those 
     ^       ^       ^  characters
               ^        each character assigned to x
      ^                 turn x back into a integer 
 ^                      sum all those digits together

Here is a less terse example:

n=123456
total=0
for ch in str(n):
    print(f'{ch:>3}')
    total+=int(ch)
    
print(f'===\n{total:>3}')

Prints:

  1
  2
  3
  4
  5
  6
===
 21
dawg
  • 98,345
  • 23
  • 131
  • 206
  • 2
    I really don't see how that answers the question... There are obviously many ways to do that, the OP is asking what is wrong with __their approach__... – Tomerikoo Dec 27 '20 at 15:31
0

You could do it even more compactly by using the map() function which in this case, applies the int function to every string representation of each digit, then each int digit is being summed by the sum() function.

Sidenote: Please don't use sum as a variable name because it's a built-in function, and you are shadowing it.

def number_adder():
    #Inputs user value. Specifically a natural number
    number = int(input('Enter a natural number: '))
    num_sum  = sum(map(int, str(number)))
    print('The sum of all digits of the value is', num_sum)

number_adder()

Output (with an input of 22222):

Enter a natural number: 22222
The sum of all digits of the value is 10
solid.py
  • 2,782
  • 5
  • 23
  • 30
0

The problem

def number_adder():
    # [...]
    
    sum += math.floor(number)
    number -= math.floor(number)
    print(number)
    # Prints: 0.22219999999999995

    # [...]

I added a print statement to check the value of number out and given the input 22222 the output for number at that point was: 0.22219999999999995. That happens because Python doesn't execute floating point operations with infinite precision, so that's the most precise value it can get for the substraction given sum and number. (Check Python error in basic subtraction? and Python error in basic subtraction? as examples).

Naturally, when looping through the decimals of number the following happens:

for digit in range(number_of_digit - 1):
  number = number * 10
  sum += math.floor(number)

  number -= math.floor(number)
0.2221999...5 <-- Adds a 2
0.221999...5 <-- Adds a 2
0.21999...5 <-- Adds a 2
0.19999...5 <-- Adds a 1

And that's the reason why you get 9 as the final number (Adding up to the previous value of 2).

Possible solution:

Replace number -= math.floor(number) in the two lines that I point out with number = round(number - math.floor(number), number_of_digit - 1) to get back the original decimal values by rounding

import math


def number_adder():
    # [...]
    sum += math.floor(number)
    # Round number to `number_of_digit - 1` decimals 
    # This will yield: `0.2222` for the original input `22222`
    number = round(number - math.floor(number), number_of_digit - 1) # (1) <---

    for digit in range(number_of_digit - 1):
        number = number * 10
        sum += math.floor(number)
        # Round `number` again here as this is a new floating point operation 
        # (number_of_digit - digit - 2) are the remaining decimal points
        number = round(number - math.floor(number), number_of_digit - digit - 2) # (2) <---

    print("The sum of all digits of the value is, ", sum)
Turtlean
  • 579
  • 4
  • 9