0

I'm a total beginner in programming. My question is what actually this code does. I think it takes the whole division result from 10, and then calculates mod 10, and prints it. The res here I think is not a built-in command in Python, and is just a variable used here, but its value is zero.

Here's the code in question:

res=0
num=int(input("Enter a postive integer:  "))
while num > 0:
    res=res+(num % 10)
    num = num // 10
    print(res)
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
Shalom .I
  • 13
  • 2

1 Answers1

0

Try running this.

res=0
num=int(input("Enter a postive integer:  "))
while num > 0:
    print("res = {0} + {1}".format(res, num % 10))
    res = res + (num % 10)
    num = num // 10
print(res)

In words, while num > 0, the digits of num are summed from right-to-left.

res starts at 0, and increases each time over the loop.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • Thanks, now I understand what it does. But I don't actually understand how it does that. I mean, which commnand here means "sums of all digits"? The "num // 10" in Python gives me the whole number result which is divised by ten, and "num % 10" gives me the remainder of the division number by ten. So what exactly here tells the program to sum up the digits? – Shalom .I Nov 12 '16 at 21:05
  • `res` is an integer. `+` adds things. `res = res +` adds onto the existing `res` value and can be re-written as `res += ` – OneCricketeer Nov 12 '16 at 21:07