No need to create the variable outside the while
with an artificial value only to enter it. You can do so:
numero = [[], []]
while True:
valor = int(input('Número: '))
if valor < 0: # número negativo
break # sai do hile
if valor % 2 == 0:
numero[0].append(valor)
else:
numero[1].append(valor)
print(f"{numero[0]}\n{numero[1]}")
while True
creates a loop infinity - in fact, it repeats itself until it is interrupted by a break
. And the break
, in this case, it is called if the value is negative, which is its output condition. Thus, it leaves the while
before entering the negative number in one of the lists, which is what you need.
Since the program will only insert positive numbers and the rest of the division by 2 will be zero or 1, you could also use the rest as the index:
numero = [[], []]
while True:
valor = int(input('Número: '))
if valor < 0: # número negativo
break # sai do hile
numero[valor % 2].append(valor)
To another answer also works, but there is a catch: the condition for the number to be valid and inserted in the lists (numero >= 0
) repeats itself three times in the code. And if you need to change this condition (for example, if the program can now accept negative numbers, and the positive ones can only be less than 100, or any other criteria), you will have to do so in these 3 places. Already using the code above, the condition is in a single point and just change there if you need.
Although it is only an exercise, it is important to think about these aspects, because avoiding this type of repetition helps a lot in the maintenance of the code - this principle is known as DRY (Don’t Repeat Yourself).
Got it, thanks. The problem was really simple.
– Talles Matos