Python in while loops | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

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)

19th Sep 2021, 7:47 PM
Nida Hanfi
Nida Hanfi - avatar
3 Answers
+ 2
Or, you could just do print(sum(int(i) for i in input()))
20th Sep 2021, 4:56 AM
David Ashton
David Ashton - avatar
+ 1
Looks good, almost. Just be certain to properly indent the while loop statements.
19th Sep 2021, 8:47 PM
Brian
Brian - avatar
0
Your code lacks indentation. Can you please put in a script on playground?
19th Sep 2021, 8:47 PM
Lisa
Lisa - avatar