am I new to the programming will you help me?

Asked

Viewed 76 times

-3

would like the result of Ifs to enter directly into the variable (Lista2) and to be printed all example numbers [1,3,2,5,5,7,8]. My code so far:

lista = []
lista2 = []
while len(lista)+1 <= 7:
 lista.append(int(input("Digite o valor: ")))
print ((lista))

    if lista[0]==lista[1]:
     lista2 = lista[0] + lista[1] 

    if lista[1]==lista[2]:
     lista2 = lista[1] + lista[2]

    if lista[2]==lista[3]:
     lista2 = lista[2] + lista[3]

    if lista[3]==lista[4]:
     lista2 = lista[3] + lista[4]

    if lista[4]==lista[5]:
     lista2 = lista[4] + lista[5]

    if lista[5]==lista[6]:
     lista2 = lista[5] + lista[6]

print(lista2)

1 answer

1


The way your code is the Lista2 variable is not of the list type, because you are assigning a sum of two int in it, then it will be int, and also if lista[0] == lista[1] and lista[2] == lista[3] the variable Lista2 will only take the last value, since it is overwriting it, if you want to create a list with the equal numbers you have to put lista2.append(lista[0]+lista[1])

Another thing is that you don’t need to do this much if, since it follows a pattern you can put in a for

for i in range(1,len(lista)):
  if lista[i-1]==lista[i]:
    lista2.append(lista[i-1]+lista[i])

python also allows you more sophisticated solutions, such as:

lista2 = [lista[i-1]+lista[i] for i in range(1,len(lista)) if lista[i-1]==lista[i]]
  • obg for the tip helped a lot

Browser other questions tagged

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