Why does this code give no output? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why does this code give no output?

I need to find the sum of the digits in a number. n = int(input()) total = 0 while n > 0: n%10 total = n + n print(total)

18th Sep 2021, 3:07 PM
James Murphy
James Murphy - avatar
13 Answers
+ 8
James Murphy , the program needs to have 2 divudions: ▪︎modulo division '%' ▪︎floor division '//' n = int(input()) total = 0 while n > 0: digit = n % 10 total += digit n = n // 10 print(total)
18th Sep 2021, 3:33 PM
Lothar
Lothar - avatar
+ 3
James Murphy, I figured it out. Sololearn doesn't output when it knows that there is an infinite loop... the print statement is after the infinite loop, thus it'll never print.
18th Sep 2021, 3:20 PM
Yahel
Yahel - avatar
0
Maybe do: n = n % 10
18th Sep 2021, 3:09 PM
Yahel
Yahel - avatar
0
That doesn't seem to help, still no output.
18th Sep 2021, 3:11 PM
James Murphy
James Murphy - avatar
0
James Murphy, if there is no output, the problem is not in code.. you should have an output because you have a print inside a global scope. Check the area you are working with
18th Sep 2021, 3:15 PM
Yahel
Yahel - avatar
0
Its within a sololearn activity on my phone app so not a lot I can do about the area
18th Sep 2021, 3:16 PM
James Murphy
James Murphy - avatar
0
OK, thanks. How do I make it not be an infinite loop?
18th Sep 2021, 3:25 PM
James Murphy
James Murphy - avatar
0
James Murphy, I don't know what's your need, but I can explain why you get an infinite loop: - Assume you enter 1 as input. n = n % 10 -> n = 1 n = n % 10 -> n = 1 n = n % 10 -> n = 1 ....
18th Sep 2021, 3:28 PM
Yahel
Yahel - avatar
0
OK thanks, that makes sense, I'll have a fiddle with it.
18th Sep 2021, 3:30 PM
James Murphy
James Murphy - avatar
0
Thanks very much, I can see that the floor division is needed to make n no longer be greater than 0, thus breaking the while loop. (I think)
18th Sep 2021, 3:36 PM
James Murphy
James Murphy - avatar
0
i don't understand this Guess the output of this code: things = [”text", 0, [1, 2, 8], 4.56] print(things[2][2])
19th Sep 2021, 5:13 PM
Raghul Manoharan
Raghul Manoharan - avatar
0
It would be 8 right?
19th Sep 2021, 5:25 PM
James Murphy
James Murphy - avatar
0
n=int(input("Enter your number=")) s=0 a=n while n>0: t=n%10 s=s+t n=n//10 print("\nSum of digit %i is =%i"%(a,s))
20th Sep 2021, 1:53 PM
Abhishek Kumar
Abhishek Kumar - avatar