For what it gave to understand created a loop to keep repeating the request of the data until it is valid. There must be another more external loop that controls how much data was entered, I’ll ignore that part because it’s not even complete.
The problem is the else
. First, you must think that this block performs if it doesn’t fall on except
, but in fact he falls at all times, giving exception or not, and does not seem to be what he wishes.
Actually it seems that these if
s are not part of the validation, it is a code that must execute whenever the data is valid and that loop is about being invalid, then that if
should be out of the loop, it should run every time just after it left the loop.
The only decision to make there is whether or not to continue in the loop. The except
all right, if error should ask again, then you need to do nothing. If no error should close the loop with a break
.
Something that you may not know is that if the normal flow does not perform, then you can put the break
in the normal stream, it will only be executed if there is no error, which is exactly what you want, if something valid is entered you must exit the loop. The exception is an exceptional flow control, if its logic is confused it loses its reason to exist.
I could keep the continue
, but I thought it more semantic to have the pass
, because it must continue the normal flow from the li and not skip everything it has after the code. But it can be misinterpreted my according to the problem presented (there are not so many details).
listaidademenorde18 = []
listaidademaiorde18 = []
while True:
try:
idade = int(input('Digite a idade da pessoa: '))
break
except ValueError:
pass
if idade < 18:
listaidademenorde18.append(idade)
else:
listaidademaiorde18.append(idade)
print(listaidademenorde18)
print(listaidademaiorde18)
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
I take this opportunity to conceptualize something that the question misunderstands.
You’re not typing a int
or other tip ode given when the input()
asks for a data. You’re always typing a text, that’s all. There are texts that can be transformed into an integer numeric data because all characters are numeric digits. Then being possible to make the conversion you will have a data that will be of type Number
and that it will be whole because it used a conversion function that generates an integer value always, if possible, if it is not possible it generates an exception, then the input()
has nothing to do with it. And there is no variable int
.