How to calculate output of sum of digits in a given input number? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

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

17th Oct 2020, 3:51 AM
Rahul Prasad
Rahul Prasad - avatar
13 Answers
+ 2
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
17th Oct 2020, 4:06 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 3
print(sum(map(int, input().strip())))
17th Oct 2020, 10:34 AM
QTWizard
+ 3
QTWizard Clever! I was thinking: num = int(input() or 2345) print(sum(int(i) for i in str(num)))
17th Oct 2020, 10:42 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 3
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. 😁
17th Oct 2020, 10:57 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 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)
17th Oct 2020, 4:50 AM
Rahul Prasad
Rahul Prasad - avatar
+ 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.
17th Oct 2020, 4:09 AM
LastSecond959
LastSecond959 - avatar
+ 1
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
17th Oct 2020, 4:11 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 1
Rik Wittkopp Well, you have a point.
17th Oct 2020, 4:13 AM
LastSecond959
LastSecond959 - avatar
+ 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").
17th Oct 2020, 10:54 AM
QTWizard
+ 1
total= sum(list(map(int,input()))) this is a python trick to calculate the sum of digits of the number
17th Oct 2020, 6:34 PM
Vinay Khatri
Vinay Khatri - avatar
0
can you give me the answer in the code form ....
17th Oct 2020, 4:15 AM
Rahul Prasad
Rahul Prasad - avatar
0
Why don't you try it? I don't want to ruin the surprise or spoil anything.
17th Oct 2020, 4:19 AM
LastSecond959
LastSecond959 - avatar
0
i m trying..... but i m getting confuse with using proper syntex.....
17th Oct 2020, 4:21 AM
Rahul Prasad
Rahul Prasad - avatar