简体   繁体   中英

How do I use the for loop and append method to prompt the user to add multiple string inputs to the list

I have to write a program that will ask users to add the following members to the list; maria and SayeSoft. after the user added these two members to the list the loop just continues to ask the user again and again instead of executing the program next to it.

This is my code:

my_list = ["Adam", "Isa"]

for i in my_list:
    my_list.append(input("Enter the name:" )) 

print(my_list) 
```![enter image description here](https://i.stack.imgur.com/TYR8i.png)

Maybe you could ask the user how many names they would like to add first:

def get_int_input(prompt: str) -> int:
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print("Error: Enter an integer, try again...")

my_list = ["Adam", "Isa"]
print(f"{my_list = }")
num_names_to_add = get_int_input("How many names would you like to add? ")
for i in range(1, num_names_to_add + 1):
    my_list.append(input(f"Enter name {i} to add: "))
print(f"{my_list = }")

Example Usage:

my_list = ['Adam', 'Isa']
How many names would you like to add? a
Error: Enter an integer, try again...
How many names would you like to add? 2
Enter name 1 to add: Maria
Enter name 2 to add: SayeSoft
my_list = ['Adam', 'Isa', 'Maria', 'SayeSoft']
ask=int(input("how many names do you wish to add?  :  "))
names=[]
for i in range(ask):
    name=input('enter name  ')
    names.append(name)
print(names)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM