1

i just started programming in Python and i'm trying to do a program that prints names n times through a while loop, the condition is when the user input yes the program keeps adding n names to a list, if the users inputs something else it simply prints all the elements added in the list

eg: list_input = "Enrique"
count = 3 #Times
lista = ['Enrique', 'Enrique', 'Enrique']

def nameTries():
list_input = input("Enter the name:")
lista = []
count = int(input("How many times you want to repeat it?"))
lista.append(f'{list_input * count}')
confirm = input("Wanna add more? yes/no")
while confirm == "yes":
    list_input = input("Enter the name:")
    count = int(input("How many times you want to repeat it?"))
    lista.append(f'{list_input * count}')
    confirm = input("Wanna add more? yes/no")
    if confirm != "yes":
        print(lista)
        break
else:
    print(lista)

the problem is it's adding ONLY in an element of the list like this:

 >>>['EnriqueEnriqueEnrique']

how can i solve this? Thanks in advance.

Spec95
  • 21
  • 2

1 Answers1

0

the append method only adds 1 element to a list. If you want to add several elements at once, you must concatenate, which is done with the + operator.

Also, your looping procedure is not very "sexy" because the instructions are the same two times. You could do it better like this :

def nameTries():
    lista = []
    while True:
        list_input = input('Enter the name: ')
        count = int(input('How many times you want to repeat it? '))
        lista += [list_input] * count
        confirm = input('Wanna add more? (y/n): ')
        if confirm != 'y':
            return lista
>>> nameTries()
Enter the name: Enrique
How many times you want to repeat it? 3
Wanna add more? (y/n): y
Enter the name: Pedro
How many times you want to repeat it? 5
Wanna add more? (y/n): n
['Enrique', 'Enrique', 'Enrique', 'Pedro', 'Pedro', 'Pedro', 'Pedro', 'Pedro']
Mateo Vial
  • 658
  • 4
  • 13