-2

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)

2 Answers2

1

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.

DanDayne
  • 154
  • 6
0

It's important to use parentheses when working with mixed operators because operator precedence can lead to unintended results. In Python, % and // have the same precedence so the expression is evaluated from left to right. Refer to 6.17 in the Python Documentation for more detailed information on language specific precedence.

In your above code, since it's evaluated from left to right, the floor division will always occur before the modulo operation so no ZeroDivsionError can occur. But to answer your question, you can always use a try and catch block to catch the ZeroDivisionError and handle it on your own.

number = int(input())
try:
  a = number // 100
  b = number // (10 % 10)
  c = number % 10
  print(a + b + c)
except ZeroDivisionError:
    print("Please enter another number that's not a multiple of 10.")
    number = int(input())
wovano
  • 4,543
  • 5
  • 22
  • 49
bpiekars
  • 53
  • 5
  • First of all, Python != JavaScript, so it doesn't make sense to show it as a JavaScript (I fixed that for you). Secondly, if I run this code and enter 7, it prints "Please enter another number that's not a multiple of 10.", and as far as I know, 7 is not a multiple of 10 ;-) – wovano Apr 23 '22 at 08:05