0
Getting sum of digits in a number with a while loop.
Code: num = 123 sum = 0 while n > 0: sum += n % 10 n //= 10 print(sum) Question: How do we get last digit to the left (1 in 123)? I understand how we get (3 + 2) but not (3+2+1). Can someone explain in a visible way? Thanks.
5 ответов
+ 6
First it will get the remainder by using modulus operator (%) to a number by 10, in other words it will get the last digit.
▫️e.g. 123 % 10 ---> 3
Then after we get the last digit, we will use floor division (//) and divide it by 10 to remove the last digit.
▫️e.g. 123 // 10 ---> 12
Then repeat the process until we have no digits left or 0.
__________________________
INPUT = 123
ℹ️---FIRST LOOP---ℹ️
🔹123 % 10 ---> 3 (add to sum)
🔹123 // 10 ---> 12 (last digit '3' removed)
🔸sum is now 3
🔸n is now 12
ℹ️---SECOND LOOP---ℹ️
🔹12 % 10 ---> 2 (add to sum)
🔹12 // 10 ---> 1 (last digit '2' removed)
🔸sum is now 5
🔸n is now 1
ℹ️---THIRD LOOP---ℹ️
🔹1 % 10 ---> 1 (add to sum)
🔹1 // 10 ---> 0
🔸sum is now 6
🔸n is now 0
_______🔻BREAK🔻________
Since n is now 0 the while loop condition will become False and the loop will end or break.
And the final value of n is 6.
Therefore the sum of digits in 123 is 6.
If this is still unclear, please feel free to ask. Thanks.
+ 2
n= 123
sum = 0
while n > 0:
sum += n % 10
n //= 10
print(sum)
+ 1
Just write n instead of num in declaration or vice versa
0
Cyan Great way of answering.
I had to google how 1 is the remainder after 1 is divided by 10.
Proof:
dividend = (divisor x quotient) + remainder.
1 = (10 x 0) + 1