Doubt about lists and repetitions ! (Python)

Asked

Viewed 77 times

-3

Hello, I am doubtful in a matter of a list of Algorithms, it asks to create an algorithm where the user informs a certain amount of numbers and for when he type 0. At the end of the program he wants the algorithm to separate even numbers from odd.

My problem itself is that my program is not reporting the first number dialed by the user and I do not know how to solve.Below I put a photo to make it easy to view the problem. I also accept tips and criticism, I’m new in programming.

x = int(input("Digite valores"))

lista = []
lista2 = []
lista3 = []

while x != 0:
    x = int(input("Digite valores"))
    lista.append(x)

for i in range(len(lista)):
    if i%2 != 0:
        lista2.append(lista[i])
print("Os valores ímpares são",lista2)

for s in range(len(lista)):
    if s%2 == 0:
        lista3.append(lista[s])
print("Os valores pares são",lista3)

screenshot of the code

  • 2

    Edit your question to remove code as image. As you can read in this post, image format codes is not a good idea.

  • 1

    The photo does not facilitate visualization, but rather makes it difficult and prevents anyone who wants to test their code to copy and paste it into the debugger.

2 answers

1

The first entered value is not added to the list because you didn’t add it to the list before entering while and reading again. In order for all values to be read and added in the list you must read only inside the while.
I did a check to not add zero to the list too:

<!-- language: python -->
lista = []
lista2 = []
lista3 = []
x = None # Inicia um valor qualquer para que a condição do while seja verdadeira

while x != 0:
    # Toda leitura do x que for feita será armazenada na lista
    x = int(input("Digite valores: "))
    if x != 0:
        lista.append(x)

for i in range(len(lista)):
    if i % 2 != 0:
        lista2.append(lista[i])
print("Os valores ímpares são: ", lista2)

for s in range(len(lista)):
    if s % 2 == 0:
        lista3.append(lista[s])
print("Os valores pares são: ", lista3)

Grudge:

inserir a descrição da imagem aqui

0


This is happening because the first element (kind of purposefully) is not placed on the list. I suggest you take the first line of code, change while != 0 by a looping "infidel": while True: and put a condition inside the looping, so that if the number entered by the user is 0 the program exits the looping.

  • I remade the program with the tips and it worked super well ! Thank you Alex !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.