Search code examples
pythondivision

Given a three-digit number, find the sum of its digits. Python


This is a simple python exercise and the code already works but I was wondering, if the remainder 10 % 10 is zero, how can i divide a given number by zero and get something out of it other than an error? It is probably trivial but I just cant realize what is going on.

number = int(input())
a = number // 100
b = number // 10 % 10
c = number % 10
print(a + b + c)

Solution

  • Well, you don't really divide by zero anywhere in that example. If you are referring to line b = number // 10 % 10, then what really happens is that number is divided by 10 and the result of that is given into the modulo, which translates to "remainder after division by 10". I think you understood the order of operations wrong on that line, which led you to believe that division by 0 could occur. It can't.