How to calculate output of sum of digits in a given input number? | SoloLearn: Learn to code for FREE!

+1

How to calculate output of sum of digits in a given input number?

10/17/2020 3:51:52 AM

Rahul Prasad

13 Answers

New Answer

+1

There are a couple of ways to do this. One way is: 1. Turn your integer into a string 2. Iterate through the string to get each digit 3. Turn each digit back into an integer 4a. Append these digits into an empty list, then sum(list) 4b. Or have a value similar to total =0 Then : total += digits

+3

print(sum(map(int, input().strip())))

+2

Thanks for the hint.... i did it.... n=int(input()) total =0 while(n>0): dig=n%10 total =total+dig n=n//10 print(total)

+2

QTWizard Clever! I was thinking: num = int(input() or 2345) print(sum(int(i) for i in str(num)))

+2

QTWizard True, that would be the more streamlined, but my interpretation of the original question was that an integer would be the input, hence all the conversions. 😁

+1

Rik Wittkopp While iterating through the string, if you can turn the digit to integer, why don't you just do the sum in there? I think there's no need to make a list of it since the OP only asking "How to calculate". Not saying that you're wrong but, you get what I mean.

+1

Rik Wittkopp Well, you have a point.

+1

Rik Wittkopp yeah, you can use generator expressions.👍 But you are doing some redundant operations(convert str to int then back to str) You can write: num = input() or "2345" print(sum(int(i) for i in num)) Or simply: print(sum(int(i) for i in input() or "2345").

+1

total= sum(list(map(int,input()))) this is a python trick to calculate the sum of digits of the number

0

LastSecond959 You are correct, but how to explain all that to a beginner without also supplying a code as reference. I was trying to give simple hints on the process

0

can you give me the answer in the code form ....

0

Why don't you try it? I don't want to ruin the surprise or spoil anything.

0

i m trying..... but i m getting confuse with using proper syntex.....