Python in while loops | Sololearn: Learn to code for FREE!


Python in while loops

The given program calculates and outputs the number of digits in a given number using a while loop. During each iteration, the loop uses floor division to divide the given number by 10, thus dropping one digit. The process continues until the number has no more digits (n>0). You need to change the code to calculate and output the sum of all digits of the input number. My code is: n = int(input()) sum = 0 while n > 0: x = n % 10 sum += x n = n // 10 print(sum)

9/19/2021 7:47:52 PM

Nida Hanfi

3 Answers

New Answer


Or, you could just do print(sum(int(i) for i in input()))


Looks good, almost. Just be certain to properly indent the while loop statements.


Your code lacks indentation. Can you please put in a script on playground?