0
Hey i got a program to get sum of digits but can't understand it .the commented one is the way I understand please explain other
num = int(input( )) sum = 0 while num > 0: # d = num%10 # num = num//10 #sum += d num,sum = num//10,sum+(num%10) print("The sum of digits of number is",sum)
4 Antworten
+ 5
Here's my best attempt on explaining this.
Basically,
num, sum = num//10, sum + (num%10)
is the same as
sum, num = sum + (num%10), num//10
and also the same as
sum += num%10
num = num//10
but NOT the same as
num = num//10
sum += num%10
Basically, on the oneliner shortcut, the calculations on the right side of the equal sign are calculated first before they are assigned to the variables. So, if the input is 123,
num, sum = 12, 0+3
num, sum = 1, 3+2
num, sum = 0, 5+1
Therefore, after three iterations
sum = 6.
I hope that was clear. :)
+ 5
They are the same.
var1, var2 = calculation1, calculation2 is the same as:
var1 = calculation1
var2 = calculation2
num, sum = num//10, sum + (num%10) is the same as:
num = num//10
sum = sum + (num%10)
+ 1
thanks a lot Jonathan Pizarra I guess my doubt was if on the left side first num's value is altered then sum would be too.
Now it's all clear thanks again :-D:-D
0
thanks Paul Jacobs but there is still some doubt which I can't ask (cos I don't have proper words to ) can you please give an example using a number like 123? pls. :'(