如何使用for循环和append方法提示用户向列表中添加多个字符串输入



我必须编写一个程序,要求用户将以下成员添加到列表中;玛丽亚和SayeSoft。在用户将这两个成员添加到列表后,循环只是继续一次又一次地询问用户,而不是执行旁边的程序

这是我的代码:

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)
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)

也许你可以问用户他们想先添加多少个名称:

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 = }")

示例用法:

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']

最新更新