2016-11-20 239 views
0

我想设置用户可以输入名称的限制。这是我遇到困难的地方。我如何设置用户可以输入到列表中的名称限制为10,并限制他们不再进入?限制Python列表中输入的数量

names = [] 

print ('1 = Add Name ') 
print ('2 = Display List ') 
print ('3 = Quit ') 

while True: 

    option = input('What would you like to do: ') 

    if option == '1': 

     name= input('Enter name: ') 

     names.append(name) 
+0

那你试试这么远吗?您的代码不会显示限制输入的尝试。当你运行它时发生了什么?你预期会发生什么?你有什么特别的问题? – Robert

回答

2

你可以这样做:

if option == '1': 
    names = [input('Enter name:') for _ in range(10)] 
0

我希望下面的脚本可以帮助你:

# libraries 
import sys 

# list variable to store name 
names = [] 

# limits to save name 
limit = 10 

# function to display menu 
def menu(): 
    print("Enter 1 to add Name") 
    print("Enter 2 to show list") 
    print("Enter 3 to quit") 
    choice = int(raw_input("Enter your choice : ")) 
    return choice 

# running for infinite times till user quits 
while(True): 
    choice = menu() 
    if(choice == 1): 
     name = raw_input("Enter name to add in list : ") 
     if(len(names) > 10): 
      print("You cannot enter more names") 
     else: 
      names.append(name) 
      print(name + " - Name saved successfully.") 
    if(choice == 2): 
     print("List of names : ") 
     print(names) 
    if(choice == 3): 
     sys.exit()