¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita0
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)
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 ^^
+ 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
+ 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()]))
+ 1
Talha Jubayer I am not looking for this
Please read the question carefully
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.
0
Sum of the digits should be 9