2016-11-18 26 views
1

我有一個任務,這迫使我在滿足條件時忽略某些變量。基本上,我要求用戶輸入並告訴他有他的有效選擇,但過了一段時間後,最初有效的選擇不再有效。我想過做這樣的事情如果爲true,那麼在Python中忽略變量

while True: 
    choice = input('You can choose between: ', Choice1, Choice2, Choice3) 
    if choice == Choice1: 
     Choice1Counter +=1 
     break 
    elif choice == Choice2: 
     Choice2Counter +=1 
     break 
    elif choice == Choice3: 
     Choice2Counter +=1 
     break 
    else: 
     choice = input('You can choose between: ', Choice1, Choice2, Choice3) 
     continue 

有了這個,我會首先是「力」的有效選擇,如果輸入的是一個有效的選擇,我會加1到所選擇的計數器。如若反打了極限我想過做這樣的事情

if Choice1Chounter == 4: 
    #ignore Choice 1 for the rest of the Programm or until Choice1 is reset 

那麼這應該基本上意味着選擇1是由程序,這看起來有點像這樣被忽略(在我心中)

choice = Input('You can choose between: ', Choice1, Choice2, Choice3)

有了它應該基本上是「打印」出了以下運行程序時Choice1Counter命中IST限制後

You can choose between: Choice2 Choice3

我有82個有效輸入,無法真正定義全部82個!他們的組合,所以我想到了這一點,但找不到一個命令,只是忽略了本程序其餘部分的變量。

+0

使用一些變量'True/False'來控制哪個選項忽略,即'ignore = [False,False,True]'然後你可以用它來決定使用哪個元素。 – furas

+0

順便說一句:你可以使用list [0],choice [1]等'和'choice_counter [0]','choice_counter [1]'等等,然後你可以使用'for'循環來做這個元素的東西。 – furas

回答

4

您不應該爲此使用單獨的變量,而應該使用字典和當前有效的鍵的列表。

choices = ["Choice1", "Choice2", "Choice3", "Choice4"] 
counters = dict((choice, 0) for choice in choices) 

while choices: # exit when no choices left 
    choice = raw_input("Choose from %s > " % " ".join(choices)) # input in Py3 
    if choice in choices: 
     counters[choice] += 1 
     if counters[choice] == 4: 
      choices.remove(choice) 
    else: 
     print("That choice is not valid. Try again") 
+0

非常感謝您的幫助。我只是試了一下,它完美的作品。 – Ron