Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I fix sum of digits of a number code not entering an infinite loop?

I don’t understand why it enters an infinite loop. I stated that: if a % 10 == 0: it should break the loop but it doesn’t seem to do so. Could someone explain why this happens and why it is not correct and the solution. Thank you!

a = int(input())
total = 0
while a>0:
    rest = a % 10
    total += rest
    if rest == 0:
        break

print(total)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

It is running for infinite times because of logical error. value of a is not decreasing.
you are checking for remainder, suppose value of a is 230. then at first iteration rest will be 0 and your output will be also 0 (correct sum will be 5).

correct code will be :-

a = int(input())
total = 0
while a>0:
    rest = a % 10
    total += rest
    a=a//10
print(total)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading