2011-03-10 86 views
1

我正嘗試在Python中創建一個簡單的冒險遊戲。我來到一個地步,我要問用戶是否希望選擇選項A或B和正在使用while循環,試圖做到這一點:Python冒險遊戲 - >在一個while循環中選擇A或B不工作!

AB = input("A or B?") 

while AB != "A" or "a" or "B" or "b": 
    input("Choose either A or B") 

if AB == "A" or "a": 
    print("A") 
elif AB == "B" or "b": 
    print("B") 

的一點是,不管你是什麼輸入,問題「選擇A或B」出現。我究竟做錯了什麼?

+1

您可以在代碼中修復縮進嗎?現在,這只是無效的代碼。 – 2011-03-10 19:35:08

回答

5

while語句評估的條件語句or,這始終是爲您提供的字符串如此。

while AB != "A" or "a" or "B" or "b": 

表示:

while (AB != "A") or "a" or "B" or "b": 

非空字符串總是爲真,所以寫or "B"永遠是正確的,總是會要求輸入。更好地寫出:

while AB.lower() not in ('a','b'): 
+0

工作就像一個魅力。非常感謝你! – EdenC 2011-03-10 19:39:59

3

AB != "A" or "a" or "B" or "b" 應該 AB.upper() not in ('A','B')

2
AB != "A" or "a" or "B" or "b" 

被解釋爲

(AB != "A") or ("a") or ("B") or ("b") 

而且由於"a"總是true,這種檢查的結果永遠是true

+0

'/和自「A」/和自「a」/' – delnan 2011-03-10 19:41:49

1

這將是更好的使用:

AB = raw_input("A or B?").upper() 

然後not in構建正如其他人建議。

1

使用raw_input()功能,相反,這樣的:

ab = raw_input('Choose either A or B > ') 
while ab.lower() not in ('a', 'b'): 
    ab = raw_input('Choose either A or B > ') 

input()預計Python表達式作爲輸入;根據Python文檔,它相當於eval(raw_input(prompt))。只需使用raw_input(),以及此處發佈的其他建議。

+1

看起來他正在使用Python 3,在這種情況下,input()實際上是他需要使用的,如果我沒有弄錯的話。 – 2011-03-10 19:46:33

+0

我明白了。我沒有跳到3 ... – 2011-03-10 20:04:43

0
try: 
    inp = raw_input # Python 2.x 
except NameError: 
    inp = input  # Python 3.x 

def chooseOneOf(msg, options, prompt=': '): 
    if prompt: 
     msg += prompt 
    options = set([str(opt).lower() for opt in options]) 
    while True: 
     i = inp(msg).strip().lower() 
     if i in options: 
      return i 

ab = chooseOneOf('Choose either A or B', "ab") 

lr = chooseOneOf('Left or right', ('left','right'))