2016-12-28 62 views
0

我正在學習與LPTHW蟒蛇,我試圖建立自己的遊戲作爲練習36.我希望用戶輸入一個特定的字符串來自10個學科的集合。我可以將輸入與定義的列表進行比較,但我不能將用戶限制爲僅限5個項目。相反,我可以限制用戶只有五個輸入,但不能同時執行這兩個。蟒蛇 - 比較用戶輸入與列表並追加到一個新的列表limitng入口項目

我創建的學科名單(原字符串,名稱

discipline_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 

然後,我創建了一個空列表

your_disciplines = [] 

下面是用戶輸入與discipline_list比較和附加用戶輸入到一個新的代碼空列表(來自其他答案的代碼)

while True: 
    d = raw_input("enter your choice of discipline >> ") 
    d = str(d) 

    found_d = False 
    for i in discipline_list: 
     if d == i: 
      found_d = True 

    if found_d: 
     your_disciplines.append(d) 
    else: 
     print("Incorrect entry") 

我可以使用for-loop用於限制用戶輸入,但是我無法將其與比較結合使用。我所有的嘗試都跑了五次以上。

for d in range(0, 5): 

任何幫助將不勝感激。

回答

0

要結合這兩個條件,檢查your_disciplines長度爲while循環狀態,當你有5

while len(your_disciplines) < 5: 
    d = raw_input("enter your choice of discipline >> ") 
    d = str(d) 

    if d not in your_disciplines: 
     your_disciplines.append(d) 
    else: 
     print("Incorrect entry") 
+0

您的代碼simlify它唯一的出口真的很好。我只需做一個簡單的改變來檢查用戶條目是否在主列表中,並添加條件來檢查條目是否已經不在新用戶列表中(因此用戶不能重複正確的輸入)。現在它的功能非常好,謝謝 '如果d在discipline_list中,而不是在your_disciplines中:' 'your_disciplines.append(d)' –

0

如果你想使用while循環,你可以試試:

num = input("Enter your disciplines number >> ") # This is not required if you want to fix num to 5 
j = 0 

while j < int(num): 
    d = raw_input("enter your choice of discipline >> ") 
    d = str(d) 

    found_d = False 
    for i in discipline_list: 
     if d == i: 
      found_d = True 

    if found_d: 
     your_disciplines.append(d) 
    else: 
     print("Incorrect entry") 
    j += 1 

一些注意事項:

相反的:

for i in discipline_list: 
    if d == i: 
     found_d = True 

你可以這樣做:

if d in discipline_list: 
    found_d = True 

另外,您不需要使用found_d變量。

簡化代碼可能是:

num = input("Enter your disciplines number >> ") 
i = 0 

while i < int(num): 
    d = raw_input("enter your choice of discipline >> ") 
    d = str(d) 

    if d in discipline_list: 
     your_disciplines.append(d) 
    else: 
     print("Incorrect entry") 
    i += 1