The division should be within the attempt, after the attempt is over and has already dealt with the possible mistake that has no way to happen, there is no point in making the division because there the error will not be dealt with. It would be something like that:
N = int(input())
for i in range(0, N):
try:
X, Y = input().split(" ")
X = float(X)
Y = float(Y)
divisao = X / Y
print(divisao)
except ZeroDivisionError:
print('divisao impossivel')
But that’s not right.
There are other errors that have not been dealt with, and it is complicated to deal with without the exception.
And I think an error that is easily detected should do so instead of letting the exception burst. So contrary to what is written in the question capture the exception is not the only alternative to solve this.
And if you make a mistake I imagine you shouldn’t go into counting items like you’re doing.
It’s not a mistake, but Python’s people picked up this sad way of getting the data in a row only that encourages typing wrong things. I would change that, but it may be that exercise asks like this, which is a way of teaching to do confusing things, I would rethink something that goes down this path as being a good reference.
Then it would almost be this;
n = int(input())
i = 0
while i < n:
try:
x, y = input().split(" ")
x = float(x)
y = float(y)
if y != 0:
print(x / y)
i += 1
else:
print('divisao impossivel')
except ValueError:
print('formato digitado errado')
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
Actually it can still give error when you type the n
, make the treatment of this case.
Could you explain to me why this way of reading the data in a single line is not appropriate? My first programming language is Python.
– Matheus Cavalcante
Because it is very easy to type wrong, one has to know that one has to put a space.
– Maniero