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)
CodePudding user response:
Maybe you could ask the user how many names they would like to add first:
def get_int_input(prompt: str) -> int:
num = -1
while True:
try:
num = int(input(prompt))
break
except ValueError:
print("Error: Enter an integer, try again...")
return num
my_list = ["Adam", "Isa"]
print(f"my_list={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}")
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']
CodePudding user response:
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)