2016-11-20 63 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()