How to find the sum of digits of a number? (python) | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
0

How to find the sum of digits of a number? (python)

How can i make a program that take a number as an input from the user and then print the sum of the digits of that number? Like if the user inputs 55 the output should be 10 I know that while loop will be required but i don't know that how can i make use of a while loop in it!! (Please don't give the solution)

19th Feb 2021, 1:40 PM
∆BH∆Y
∆BH∆Y - avatar
6 Respuestas
+ 3
Talha Jubayer OP's not asking for sum of numbers between 1 and n (wich you could more efficienly compute as n*(n+1)/2), but the sum of digits from n... ∆BH∆Y you should iterate over digits of target number: n = int(input()) s = 0 while n: s += n%10 n = n//10 print(s) if you need a result < 10, you must add a loop (while 9 < s), assign s to n, 0 to s and redo the digit sum loop ^^
19th Feb 2021, 1:56 PM
visph
visph - avatar
+ 2
∆BH∆Y simply observe logic, Ex : n = 25, n%10=> 5 , make n = 2 by division and next repeat for n =2, n%10=2, make n =0 adding reminders 5+2 = 7
19th Feb 2021, 2:00 PM
Jayakrishna 🇮🇳
+ 2
∆BH∆Y You can also use list comprehension (similar to loop) with sum function though you have to get the input as string and not an integer. print(sum([int(x) for x in input()]))
19th Feb 2021, 3:53 PM
noteve
noteve - avatar
+ 1
Talha Jubayer I am not looking for this Please read the question carefully
19th Feb 2021, 1:55 PM
∆BH∆Y
∆BH∆Y - avatar
0
Eve’s answer is correct for the question. while loop is not the tool, the for loop is. Eve used an abbreviated for loop to turn the input into a list of the digits in it, then she used the sum function to add together all elements of the list.
19th Feb 2021, 6:50 PM
Wilbur Jaywright
Wilbur Jaywright - avatar
0
Sum of the digits should be 9
4th Oct 2022, 6:51 AM
MUGILARASI D
MUGILARASI D - avatar