'Given a three-digit number, find the sum of its digits. Python [duplicate]
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 1:[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.
Solution 2:[2]
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())
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | DanDayne |
Solution 2 | wovano |