Home > Back-end >  sum of all digits in the number by python
sum of all digits in the number by python

Time:12-18

Write a python program to calculate sum of digits of a number. and pls explain it line by line as I am new please.

I am screeching it online and found something like this :-

sum = 0
while (n != 0):
   
    sum = sum   (n % 10)
    n = n//10

I don't understand the use of these 2 line please explain it

sum = sum   (n % 10)
        n = n//10

and suggest me if you guys know any another ways to slove it quick and easily? thank you

CodePudding user response:

# Extract the last digit of the number
(n % 10)

Using the modulus operator (%) to get the remainder when n is divided by 10. (e.g., if n is 123, then n % 10 would be 3)

# Add it to the sum
sum = sum   (n % 10)

This is to just add it to the sum variable.

# Remove the last digit from the number
n //= 10

Using the floor division operator (//) to divide n by 10 and assign the result back to n. For example, if n is 123, then n // 10 would be 12.

CodePudding user response:

Prev. post has explained details each of the original code steps. It's to calculate the digit sum. (to make it quicker)

Alternatively, you could do this one-liner:

Explain: convert the number to string then loop and sum the int(x)

Note - since the sum is Python built-in - try to avoid using it as the variable name.

n = 123

digit_sum = sum(int(x) for x in str(n))  
# 6

CodePudding user response:

so basically while loop runs till n becomes 0 let's take an example given n=2438 initially sum is 0

checking is n==0 no... Enter the while loop

`sum = sum   (n % 10)` -> sum=0 8  as 2438=8 which is remainder..!
`n = n//10` -> n=243 after division as you can see the last digit is removed ..!

check is n==0 no.. enter the loop

`sum = sum   (n % 10)` -> sum=8 3  as 243=3 which is remainder..!
`n = n//10` -> n=24 after division as you can see the last digit is removed ..!

as you can see above two steps .

sum=11 4
n=2

sum=15 2
n=0

check is n==0 yes the while loop breaks..!

print the sum as you have obtained the result

As you are beginner you should come up with the simple answer like..

n=2438
n=str(n)      #   2438 converted into "2438"
total_sum_of_digit=0
for i in n:   # loop runs as it converted into string..
    total_sum_of_digit =int(i)   #converted string digit to int digit and add into total_sum_of_digit
print(total_sum_of_digit)

List comprehension is better option.. but you should go with the beginner level to the such above topics..

  • Related