Add item to list in Python

1

I want to make a program in Python in which pressing 1, print a list of colors and pressing 2, give me the option to add a new color and pressing again 1, I see the list of colors with the new addition , What should I do? This is what I have:

while True:
  print("""¡Bienvenido!
  1-Lista de colores
  2-Añadir color""")
  opcion = int(input("Opción: "))
  if opcion ==1:
    colores={"amarillo","azul","rojo"}
    print("Los colores son: ")
    print(colores)
  elif opcion ==2:
    nuevoColor = input("Introduce color: ")
    
asked by Juan 04.02.2018 в 16:41
source

1 answer

1

the lists in python are specified using [] (brackets), I see that in your code you use {} (braces) which python understands as dictionaries. p>

Stop achieving what you want

  

I want to make a program in Python in which pressing 1, print a list of colors and pressing 2, give me the option to add a new color and pressing again 1, I see the list of colors with the new addition

You must create the list before while so that it is not created again for each iteration. So the code should start like this:

colores=["amarillo","azul","rojo"]  # Las listas en python se indican con [ ]
while True:

Notice that he now uses [] instead of {}

Now we only have to add the color when the user enters "2", in that condition it would look like this:

elif opcion ==2:
    nuevoColor = input("Introduce color: ")
    colores.append(nuevoColor)

I recommend you read more about lists in python Here is the complete code:

colores=["amarillo","azul","rojo"]
while True:
print("""¡Bienvenido!
    1-Lista de colores
    2-Añadir color""")
opcion = int(input("Opción: "))
if opcion ==1:
    print("Los colores son: ")
    print(colores)
elif opcion ==2:
    nuevoColor = input("Introduce color: ")
    colores.append(nuevoColor)
    
answered by 04.02.2018 в 17:02